package com.taxshare.seller.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taxshare.freemark.utils.FreemarkUtil;
import com.taxshare.mybatis.pager.PageRequest;
import com.taxshare.mybatis.utils.DozerBeanUtil;
import com.taxshare.response.beans.Response;
import com.taxshare.seller.constant.CodeConstant;
import com.taxshare.seller.constant.PrinterConstant;
import com.taxshare.seller.entity.*;
import com.taxshare.seller.entity.excel.InvoiceCarDetailExcelEntity;
import com.taxshare.seller.entity.excel.InvoiceDetailExcelEntity;
import com.taxshare.seller.entity.excel.InvoicedExcelEntity;
import com.taxshare.seller.mapper.CancelDocDetailMapper;
import com.taxshare.seller.mapper.FphmdDetailMapper;
import com.taxshare.seller.mapper.InvoiceDetailMapper;
import com.taxshare.seller.mapper.InvoicedMapper;
import com.taxshare.seller.remote.ApiClientService;
import com.taxshare.seller.service.sst.IntJsonUtil;
import com.taxshare.seller.util.*;
import com.taxshare.seller.view.dto.*;
import com.taxshare.seller.view.vo.DownloadRedInvoiceVO;
import com.taxshare.seller.view.vo.SellerInvoiceRVO;
import com.taxshare.seller.view.vo.SellerInvoiceRespVO;
import com.taxshare.seller.view.vo.UpdateSellerInvoiceVO;
import com.taxshare.tools.constant.CommonConstant;
import com.taxshare.tools.token.UserInfoUtil;
import com.taxshare.tools.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author YANG
 * @date 2021/3/25
 * @Description:已开发票管理
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.READ_COMMITTED)
@Slf4j
public class InvoicedService extends ServiceImpl<InvoicedMapper, SellerInvoiceEntity> {

    @Value("${lqpt.ptbh}")
    private String ptbh;
    @Value("${lqpt.hexKey}")
    private String hexKey;
    @Value("${lqpt.url}")
    private String url;
    @Value("${lqpt.ip}")
    private String ip;
    @Value("${lqpt.macdz}")
    private String macdz;


    @Value("${empower.url}")
    private String empowerUrl;

    @Autowired
    InvoiceDetailService invoiceDetailService;

    @Autowired
    ApiClientService apiClientService;

    @Autowired
    SellerRedInvoiceDetailService sellerRedInvoiceDetailService;

    @Autowired
    RedTicketService redTicketService;

    @Autowired
    DocumentInfoService documentInfoService;

    @Autowired
    DocumentInfoDetailService documentInfoDetailService;

    @Autowired
    CancelDocDetailMapper cancelDocDetailMapper;

    @Autowired
    EquipmentService equipmentService;

    @Autowired
    GoodsManageService goodsManageService;

    @Autowired
    SellerDetialMergeService sellerDetialMergeService;

    @Autowired
    GoldenTaxPlateService goldenTaxPlateService;

    @Value("${zzsfp.url}")
    private String zzsfpUrl;

    @Autowired
    CommService commService;

    @Autowired
    FphmdDetailMapper fphmdDetailMapper;
    @Autowired
    InvoiceDetailMapper invoiceDetailMapper;
//    @Autowired
//    OrganizeMapper organizeMapper;
    @Autowired(required = false)
    LqHttpUtil lqHttpUtil;
    /**
     * 已开发票查询
     * SellerOrderEntity
     *
     * @param query
     * @return
     */
    public Response invoicedQuery(PageRequest<InvoicedDTO> query) {
        InvoicedDTO info = query.getInfo();
        // QueryWrapper<SellerInvoiceEntity> queryWrapper = new QueryWrapper<>();
        //InvoicedDTO invoicedDTO = query.getInfo();
//        if (StrUtil.isNotBlank(invoicedDTO.getInvoiceType())) {
//            queryWrapper.eq("invoice_type", invoicedDTO.getInvoiceType());
//        }
//        if (StrUtil.isNotBlank(invoicedDTO.getMakeInvoiceType())) {
//            queryWrapper.eq("make_invoice_type", invoicedDTO.getMakeInvoiceType());
//        }
//        if (StrUtil.isNotBlank(invoicedDTO.getInvoiceCode())) {
//            queryWrapper.eq("invoice_code", invoicedDTO.getInvoiceCode());
//        }
//        if (StrUtil.isNotBlank(invoicedDTO.getInvoiceNo())) {
//            queryWrapper.eq("invoice_no", invoicedDTO.getInvoiceNo());
//        }
//        if (StrUtil.isNotBlank(invoicedDTO.getInvoiceState())) {
//            queryWrapper.eq("invoice_state", invoicedDTO.getInvoiceState());
//        }
//        if (StrUtil.isNotBlank(invoicedDTO.getOldInvoiceCode())) {
//            queryWrapper.eq("old_invoice_code", invoicedDTO.getOldInvoiceNo());
//        }
//        if (StrUtil.isNotBlank(invoicedDTO.getOldInvoiceNo())) {
//            queryWrapper.eq("old_invoice_no", invoicedDTO.getOldInvoiceNo());
//        }
//        if (StrUtil.isNotBlank(invoicedDTO.getSellerName())) {
//            queryWrapper.like("seller_name", invoicedDTO.getSellerName());
//        }
//        if (StrUtil.isNotBlank(invoicedDTO.getSellerTaxNo())) {
//            queryWrapper.eq("seller_tax_no", invoicedDTO.getSellerTaxNo());
//        }
        if (StrUtil.isNotBlank(info.getPurchaserName())) {
            query.getInfo().setPurchaserName(info.getPurchaserName());
        }
//        if (StrUtil.isNotBlank(invoicedDTO.getPurchaserTaxNo())) {
//            queryWrapper.eq("purchaser_tax_no", invoicedDTO.getPurchaserTaxNo());
//        }
//        if (StrUtil.isNotBlank(invoicedDTO.getDocId())) {
//            queryWrapper.eq("doc_id", invoicedDTO.getDocId());
//        }
//        if (StrUtil.isNotBlank(invoicedDTO.getDocId())) {
//            queryWrapper.eq("project_code_max", invoicedDTO.getProjectCodeMax());
//        }
//        if (StrUtil.isNotBlank(invoicedDTO.getDocId())) {
//            queryWrapper.eq("room", invoicedDTO.getRoom());
//        }
//        if (StrUtil.isNotBlank(invoicedDTO.getDataSource())) {
//            queryWrapper.eq("data_source", invoicedDTO.getDataSource());
//        }
//        if (StrUtil.isNotBlank(invoicedDTO.getInvoiceDateStart()) && StrUtil.isNotBlank(invoicedDTO.getInvoiceDateEnd())) {
//            queryWrapper.between("invoice_date", invoicedDTO.getInvoiceDateStart(), invoicedDTO.getInvoiceDateEnd());
//        }
//        queryWrapper.eq("make_invoice_state", "2");
//        queryWrapper.orderByDesc("create_time");
//        IPage<SellerInvoiceEntity> sellerInvoiceEntityIPage = PageHelp.siamplePage(this, queryWrapper, query.getPage(), SellerInvoiceEntity.class);
        List<String> taxNos = commService.getTaxNumbers();
        if(StrUtil.isEmpty(query.getInfo().getSellerTaxNo())){
            query.getInfo().setSellerTaxNos(taxNos);
        }
        Page<SellerInvoiceEntity> page = new Page<>(query.getPage().getCurrentPage(),query.getPage().getPageSize());
        IPage<SellerInvoiceEntity> list = baseMapper.selectListBySql(page,query.getInfo());
        if(!list.getRecords().isEmpty()){
            list.setTotal(list.getTotal());
        }else {
            list.setTotal(0);
        }
        list.setCurrent(query.getPage().getCurrentPage());
        list.setSize(query.getPage().getPageSize());
        list.setPages(list.getPages());
        return Response.success(list);
    }

    /**
     * 已开发票详情查询
     *
     * @param query
     * @return
     */
    public Response<IPage<SellerInvoiceDetailEntity>> queryDetail(PageRequest<InvoicedDTO> query) {
        QueryWrapper<SellerInvoiceDetailEntity> queryWrapper = new QueryWrapper<>();
        IPage<SellerInvoiceDetailEntity> page = new Page<>(query.getPage().getCurrentPage(), query.getPage().getPageSize());
        String serialNo = query.getInfo().getSerialNo();
        queryWrapper.eq("serial_no", serialNo);
//        queryWrapper.orderByAsc("detail_no");
        queryWrapper.orderByAsc("invoice_sort");
        IPage<SellerInvoiceDetailEntity> sellerInvoiceDetailEntityIPage = invoiceDetailService.page(page, queryWrapper);
        return Response.success(sellerInvoiceDetailEntityIPage);
    }

    /**
     * 获取发票影像
     *
     * @param serialNo
     * @param response
     */
    public Response queryInvoiceImage(String serialNo, HttpServletResponse response) throws IOException {
        InvoiceImgUtil imageUtils = new InvoiceImgUtil();
        SellerInvoiceEntity sellerInvoiceEntity = baseMapper.selectOne(new QueryWrapper<SellerInvoiceEntity>().eq("serial_no", serialNo));
        List<SellerInvoiceDetailEntity> sellerInvoiceDetailEntities = invoiceDetailService.list(new QueryWrapper<SellerInvoiceDetailEntity>().
                eq("serial_no", serialNo).orderByAsc("invoice_sort"));
        BufferedImage invoiceImage = null;
        if (CodeConstant.INVOICETYPE_JDC.equals(sellerInvoiceEntity.getInvoiceType())){
            URL carImageUrl = this.getClass().getResource("/image/car2014.jpg");
            invoiceImage = imageUtils.makeCarInvoiceImage(sellerInvoiceEntity,sellerInvoiceDetailEntities,carImageUrl);
        }else {
            URL imageUrl = this.getClass().getResource("/image/common.jpg");
            invoiceImage = imageUtils.makeInvoiceImage(sellerInvoiceEntity, sellerInvoiceDetailEntities, imageUrl);
        }

        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(invoiceImage, "jpg", os);
        InputStream in = new ByteArrayInputStream(os.toByteArray());
        String imageStr = "data:image/jpg;base64," + FileToBase64.getBase64FromInputStream(in);
        SellerInvoiceRespVO sellerInvoiceRespVO = new SellerInvoiceRespVO();
        sellerInvoiceDetailEntities.forEach(iteam -> {
            if ("2".equals(iteam.getTaxRateMark())) {
                iteam.setZzstsgl("不征税");
            }
        });
        try {
            sellerInvoiceEntity.setInvoiceDate(DateUtil.getDateYear(sellerInvoiceEntity.getInvoiceDate()));
        } catch (Exception e) {
            sellerInvoiceEntity.setInvoiceDate(sellerInvoiceEntity.getInvoiceDate());
        }
        sellerInvoiceRespVO.setSellerInvoiceDetailEntities(sellerInvoiceDetailEntities);
        sellerInvoiceRespVO.setSellerInvoiceEntity(sellerInvoiceEntity);
        sellerInvoiceRespVO.setImageStr(imageStr);
        return Response.success(sellerInvoiceRespVO);
    }

    /**
     * 修改发票及其明细信息
     *
     * @param updateSellerInvoiceVo
     */
    public Response upSellerInvoice(UpdateSellerInvoiceVO updateSellerInvoiceVo) {
        if (updateSellerInvoiceVo.getSellerInvoiceEntity() == null
                || updateSellerInvoiceVo.getSellerInvoiceEntity().getUuid() == null) {
            return Response.error("SEL_107");
        }
        baseMapper.updateById(updateSellerInvoiceVo.getSellerInvoiceEntity());
        if (updateSellerInvoiceVo.getSellerInvoiceDetailEntities() != null
                && !updateSellerInvoiceVo.getSellerInvoiceDetailEntities().isEmpty()) {
            invoiceDetailService.updateBatchById(updateSellerInvoiceVo.getSellerInvoiceDetailEntities());
        }
        return Response.success();
    }

    /**
     * 根据票据GUID获取发票信息
     *
     * @param docId
     * @return
     */
    public Response invoicedIdsQuery(String docId) {
        if (StrUtil.isBlank(docId)) {
            return Response.error("SEL_107");
        }
        //判断docId是否已存在发票表中 存在则直接返回 不存在就同步信息 再返回
        QueryWrapper<SellerInvoiceEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("doc_id", docId);
        List<SellerInvoiceEntity> entityList = baseMapper.selectList(queryWrapper);
        if (CollectionUtil.isNotEmpty(entityList)) {
            QueryWrapper<SellerInvoiceEntity> queryCount = new QueryWrapper<>();
            queryCount.eq("doc_id", docId);
            queryCount.eq("make_invoice_state", CodeConstant.YK);
            if (baseMapper.selectCount(queryCount) == 0) {
                baseMapper.delete(queryWrapper);
                for (SellerInvoiceEntity entity : entityList) {
                    invoiceDetailService.remove(new QueryWrapper<SellerInvoiceDetailEntity>().eq("serial_no", entity.getSerialNo()));
                }
            }
        }
        entityList = baseMapper.selectList(queryWrapper);
        if (entityList == null || entityList.isEmpty()) {
            //根据doc_id查询订单及其明细信息
            DocumentInfoEntity documentEntity = documentInfoService.getOne(new QueryWrapper<DocumentInfoEntity>().eq("doc_id", docId));
            List<DocumentInfoDetailEntity> documentDetailEntityList = documentInfoDetailService.list(new QueryWrapper<DocumentInfoDetailEntity>().eq("doc_id", docId));
            if (documentEntity == null || documentDetailEntityList == null || documentDetailEntityList.isEmpty()) {
                return Response.error("SEL_107");
            }
            //查询该项目是否有合并明细需求
            List<List<DocumentInfoDetailEntity>> groupList = new ArrayList<>();
            QueryWrapper<SellerDetialMergeEntity> queryGoodsWrapper = new QueryWrapper<>();
            queryGoodsWrapper.eq("project_code_max", documentEntity.getProjectCodeMax());
            List<SellerDetialMergeEntity> sellerDetialMergeEntityList = sellerDetialMergeService.list(queryGoodsWrapper);
            if (CollectionUtil.isEmpty(sellerDetialMergeEntityList)) {
                documentDetailEntityList.stream().sorted(Comparator.comparing(DocumentInfoDetailEntity::getAmountWithoutTax, Comparator.reverseOrder()));
            } else {
                SellerDetialMergeEntity sellerDetialMergeEntity = sellerDetialMergeEntityList.get(0);
                //判断是否有拼接款项名称需要
                if ("1".equals(sellerDetialMergeEntity.getIsMergeCategoryName())) {
                    for (DocumentInfoDetailEntity entity : documentDetailEntityList) {
                        entity.setPaymentName(entity.getPaymentCategory() + "-" + entity.getPaymentName());
                    }
                }
                if (StrUtil.isBlank(sellerDetialMergeEntity.getIsMergeDetialGoodsName())) {
                    sellerDetialMergeEntity.setIsMergeDetialGoodsName("0");
                }
                if (StrUtil.isBlank(sellerDetialMergeEntity.getIsMergeDetialTaxRate())) {
                    sellerDetialMergeEntity.setIsMergeDetialTaxRate("0");
                }
                if ("0".equals(sellerDetialMergeEntity.getIsMergeDetialGoodsName()) && "0".equals(sellerDetialMergeEntity.getIsMergeDetialTaxRate())) {
                    documentDetailEntityList.stream().sorted(Comparator.comparing(DocumentInfoDetailEntity::getAmountWithoutTax, Comparator.reverseOrder()));
                } else if ("1".equals(sellerDetialMergeEntity.getIsMergeDetialGoodsName())) {
                    //以名称合并
                    documentDetailEntityList = megerDetailByGoodsName(documentDetailEntityList, documentEntity.getProjectCodeMax());
                } else {
                    //税率合并
                    QueryWrapper<GoodsManageEntity> queryGoodsWrapperName = new QueryWrapper<>();
                    queryGoodsWrapperName.eq("project_code", documentEntity.getProjectCodeMax());
                    if (0 == documentDetailEntityList.get(0).getTaxRate()) {
                        queryGoodsWrapperName.eq("tax_rate_mark", documentDetailEntityList.get(0).getTaxRateFlag());
                    }
                    queryGoodsWrapperName.eq("tax_rate", documentDetailEntityList.get(0).getTaxRate());
                    List<GoodsManageEntity> goodsList = goodsManageService.list(queryGoodsWrapperName);
                    if (CollectionUtil.isEmpty(goodsList)) {
                        return Response.error("SEL_037");
                    }
                    documentDetailEntityList = megerDetail(documentDetailEntityList, goodsList.get(0));
                }
            }
            groupList.add(documentDetailEntityList);
            //根据销方税号和发票种类代码查询单张发票开票限额
            GoldenTaxPlateInfoEntity goldenTaxPlateInfoEntity = goldenTaxPlateService.getOne(new QueryWrapper<GoldenTaxPlateInfoEntity>()
                    .eq("seller_tax_no", documentEntity.getSellerTaxNo())
                    .eq("invoice_type_no", TransformationUtil.documentInvoiceType(documentEntity.getInvoiceType())));
            if (goldenTaxPlateInfoEntity == null || StrUtil.isBlank(goldenTaxPlateInfoEntity.getSingleQuota())) {
                return Response.error("SEL_111");
            }
            Double singleQuota = Double.valueOf(goldenTaxPlateInfoEntity.getSingleQuota());
            //相等的不需要处理  不相等的处理
            for (List<DocumentInfoDetailEntity> detailList : groupList) {
                final BigDecimal[] sum = {new BigDecimal("0.00")};
                detailList.forEach(detai -> {
                    BigDecimal amountWithoutTax = new BigDecimal(detai.getAmountWithoutTax()).setScale(2, RoundingMode.UP);
                    sum[0] = sum[0].add(amountWithoutTax);
                });
                Double sumamount = sum[0].doubleValue();
                if (BigDecimalUtils.compare(singleQuota, sumamount) >= 0) {
                    this.openInvoice(documentEntity, detailList, 0, detailList.size() - 1, 0, 0, sumamount);
                } else {
                    //最后一张票金额
                    Double count = new BigDecimal(sumamount).divideAndRemainder(BigDecimal.valueOf(singleQuota))[0].doubleValue();
                    Double lastPrice = BigDecimalUtils.subtract(sumamount, BigDecimalUtils.multiply(singleQuota, count));
                    //总剩余金额
                    double sumRemainPrice = 0;
                    //已开第一张票剩下的钱
                    double remainPriceStar = 0;
                    //待开剩下的钱
                    double remainPriceEnd = 0;
                    //开到第几张发票
                    int iteamCountStar = 0;
                    //开到第几张发票
                    int iteamCountEnd = 0;
                    //以明细为维度进行遍历
                    for (int i = 0; i < detailList.size(); i++) {
                        iteamCountEnd = i;
                        //剩余+现有
                        double nowPrice = BigDecimalUtils.add(sumRemainPrice, detailList.get(i).getAmountWithoutTax());

                        if (BigDecimalUtils.compare(nowPrice, singleQuota) > 0) {
                            //计算大于次数  向下取整
                            double num = Math.floor(BigDecimalUtils.divide(nowPrice, singleQuota));
                            for (int z = 0; z < num; z++) {
                                double thisPrice = detailList.get(i).getAmountWithoutTax();
                                double thisSum = 0;
                                //直接开票
                                if (z == 0) {
                                    thisSum = BigDecimalUtils.subtract(nowPrice, singleQuota);
                                    thisPrice = BigDecimalUtils.subtract(thisPrice, thisSum);
                                    this.openInvoice(documentEntity, detailList, iteamCountStar, iteamCountEnd, remainPriceStar, thisPrice, lastPrice);
                                } else {
                                    thisSum = BigDecimalUtils.subtract(thisSum, singleQuota);
                                    this.openInvoice(documentEntity, detailList, i, i, 0, singleQuota, lastPrice);

                                }
                            }
                            //判断是否有剩余
                            double cs = BigDecimalUtils.subtract(nowPrice, BigDecimalUtils.multiply(singleQuota, num));
                            if (BigDecimalUtils.compare(cs, 0) == 0) {
                                sumRemainPrice = 0;
                                remainPriceStar = 0;
                                remainPriceEnd = 0;
                            } else {
                                //判断是否是最后一次遍历
                                if (i == (detailList.size() - 1)) {
                                    this.openInvoice(documentEntity, detailList, i, i, 0, cs, lastPrice);
                                } else {
                                    sumRemainPrice = cs;
                                    remainPriceStar = cs;
                                    remainPriceEnd = 0;
                                }
                            }
                            //记录开到第几张
                            iteamCountStar = i;
                        } else if (BigDecimalUtils.compare(nowPrice, singleQuota) == 0) {
                            //直接开票
                            this.openInvoice(documentEntity, detailList, iteamCountStar, i, remainPriceStar, 0, lastPrice);
                            sumRemainPrice = 0;
                            remainPriceStar = 0;
                            remainPriceEnd = 0;
                            iteamCountStar = i;
                        } else {
                            //判断是否是最后一次 是最后一次则开票 不是不处理
                            if (i == (detailList.size() - 1)) {
                                this.openInvoice(documentEntity, detailList, iteamCountStar, i, remainPriceStar, 0, lastPrice);
                            }
                        }
                    }
                }
            }
        }
        //重新查询发送给前端
        entityList = baseMapper.selectList(queryWrapper);
        List<String> serialNos = entityList.stream().map(SellerInvoiceEntity::getSerialNo).collect(Collectors.toList());
        return Response.success(serialNos);
    }

    /**
     * 同步订单方法
     *
     * @param documentEntity  订单信息
     * @param detailList      订单明细信息
     * @param iteamCountStar  开票到第几张开始
     * @param iteamCountStar  开票到第几张结束
     * @param remainPriceStar 已开第一张票剩下的钱
     * @param remainPriceEnd  开票金额
     * @param lastPrice       最后一张票金额
     */
    private void openInvoice(DocumentInfoEntity documentEntity, List<DocumentInfoDetailEntity> detailList, int iteamCountStar, int iteamCountEnd, double remainPriceStar, double remainPriceEnd, double lastPrice) {
        List<DocumentInfoDetailEntity> newDetailList = new ArrayList();
        //税率
        Double taxRate = detailList.get(0).getTaxRate();

        //初始赋值
        if (remainPriceEnd != 0) {
            detailList.get(iteamCountEnd).setAmountWithoutTax(remainPriceEnd);
        }
        if (iteamCountStar == iteamCountEnd) {
            newDetailList.add(detailList.get(iteamCountStar));
        } else if ((iteamCountStar + 1) == iteamCountEnd) {
            if (remainPriceStar != 0) {
                detailList.get(iteamCountStar).setAmountWithoutTax(remainPriceStar);
            }
            if (remainPriceEnd != 0) {
                detailList.get(iteamCountEnd).setAmountWithoutTax(remainPriceEnd);
            }
            newDetailList.add(detailList.get(iteamCountStar));
            newDetailList.add(detailList.get(iteamCountEnd));
        } else {
            newDetailList.add(detailList.get(iteamCountStar));
            newDetailList.add(detailList.get(iteamCountEnd));
            iteamCountStar += 1;
            iteamCountEnd -= 1;
            for (int i = iteamCountStar; i <= iteamCountEnd; i++) {
                newDetailList.add(detailList.get(i));
            }
        }
        //开最后一张票
        if (iteamCountStar == detailList.size()) {
            if (detailList.size() > 1) {
                for (int i = 0; i < detailList.size() - 1; i++) {
                    lastPrice = BigDecimalUtils.subtract(lastPrice, detailList.get(i).getAmountWithoutTax());
                }
                detailList.get(detailList.size() - 1).setAmountWithoutTax(lastPrice);
            } else {
                detailList.get(0).setAmountWithoutTax(lastPrice);
            }
        }
        //统一处理税额
        //合计金额
        final double[] sumAmountWithoutTax = {0};
        //合计税额
        final double[] sumTaxAmount = {0};
        //合计价税合计
        final double[] sumAmountWithTax = {0};
        newDetailList.forEach(iteam -> {
            double taxAmount = new BigDecimal(BigDecimalUtils.multiply(iteam.getAmountWithoutTax(), taxRate)).setScale(2, RoundingMode.HALF_UP).doubleValue();
            double amountWithTax = new BigDecimal(BigDecimalUtils.multiply(iteam.getAmountWithoutTax(), BigDecimalUtils.add(1, taxRate))).setScale(2, RoundingMode.HALF_UP).doubleValue();
            iteam.setTaxAmount(String.valueOf(taxAmount));
            iteam.setAmountWithTax(amountWithTax);
            sumAmountWithoutTax[0] = BigDecimalUtils.add(sumAmountWithoutTax[0], iteam.getAmountWithoutTax());
            sumTaxAmount[0] = BigDecimalUtils.add(sumTaxAmount[0], taxAmount);
            sumAmountWithTax[0] = BigDecimalUtils.add(sumAmountWithTax[0], amountWithTax);
        });
        documentEntity.setAmountWithoutTax(sumAmountWithoutTax[0]);
        documentEntity.setTaxAmount(String.valueOf(sumTaxAmount[0]));
        documentEntity.setAmountWithTax(sumAmountWithTax[0]);//价税合计
        //生成唯一流水号
        String serialNo = UUIDUitl.UUID32(false);
        //把订单信息转换成发票信息并保存
        SellerInvoiceEntity entity = this.documentToSeller(documentEntity, serialNo);
        baseMapper.insert(entity);
        List<SellerInvoiceDetailEntity> newList = new ArrayList<>();
        //项目编码
        String projectCodeMax = documentEntity.getProjectCodeMax();
        for (DocumentInfoDetailEntity documentDetailEntity : newDetailList) {
            SellerInvoiceDetailEntity sellerInvoiceDetailEntity = this.documentDetailToSellerDetail(documentDetailEntity, serialNo, projectCodeMax);
            newList.add(sellerInvoiceDetailEntity);
        }
        invoiceDetailService.saveBatch(newList);
    }


    /**
     * 订单信息转换发票信息
     *
     * @param entity 订单信息
     * @return 发票信息
     */
    private SellerInvoiceEntity documentToSeller(DocumentInfoEntity entity, String serialNo) {
        if (entity == null) {
            return null;
        }
        SellerInvoiceEntity invoiceEntity = new SellerInvoiceEntity();
        invoiceEntity.setUuid(UUIDUitl.UUID32(false));
        invoiceEntity.setDocId(entity.getDocId());
        invoiceEntity.setSerialNo(serialNo);
//        entity.getReceiDate();
//        entity.getOrderState();
        invoiceEntity.setRoom(entity.getRoom());
        invoiceEntity.setProjectMax(entity.getProjectMax());
        invoiceEntity.setProjectCodeMax(entity.getProjectCodeMax());
        invoiceEntity.setRemark(entity.getRemark());
        invoiceEntity.setPayee(entity.getReceiver());
        invoiceEntity.setReviewer(entity.getAuditor());
        invoiceEntity.setDrawer(entity.getInvoicer());
        invoiceEntity.setSellerAddressTel(entity.getSellerTelAddress());
        invoiceEntity.setSellerBankAccount(entity.getSellerBank());
        invoiceEntity.setPurchaserAddressTel(entity.getPurchaserTelAddress());
        invoiceEntity.setPurchaserBankAccount(entity.getPurchaserBank());
        invoiceEntity.setTotalSum(entity.getAmountWithoutTax().toString());
        invoiceEntity.setTotalTax(entity.getTaxAmount().toString());
        invoiceEntity.setTotalSumTax(entity.getAmountWithTax().toString());
        invoiceEntity.setInvoiceType(TransformationUtil.documentInvoiceType(entity.getInvoiceType()));
        invoiceEntity.setMakeInvoiceType(entity.getAmountWithoutTax() >= 0 ? "0" : "1");
        invoiceEntity.setMakeInvoiceState("0");
        invoiceEntity.setInvoiceState("0");
        invoiceEntity.setCreateUserid(UserInfoUtil.getUserID());
        invoiceEntity.setSellerName(entity.getSellerName());
        invoiceEntity.setSellerTaxNo(entity.getSellerTaxNo());
        invoiceEntity.setPurchaserName(entity.getPurchaserName());
        invoiceEntity.setPurchaserTaxNo(entity.getPurchaserTaxNo());
        invoiceEntity.setDataSource("1");
        invoiceEntity.setReviewer("");
        return invoiceEntity;
    }

    /**
     * 订单明细信息转换发票明细信息
     *
     * @param entity 订单明细信息
     * @return 发票明细信息
     */
    private SellerInvoiceDetailEntity documentDetailToSellerDetail(DocumentInfoDetailEntity entity, String serialNo, String projectCodeMax) {
        if (entity == null) {
            return null;
        }
        SellerInvoiceDetailEntity invoiceEntity = new SellerInvoiceDetailEntity();
        invoiceEntity.setSerialNo(serialNo);
        invoiceEntity.setUuid(UUIDUitl.UUID32(false));
        invoiceEntity.setGoodsName(entity.getPaymentName());
        invoiceEntity.setModel(entity.getItemSpec());
        invoiceEntity.setUnit(entity.getQuantityUnit());
        if (entity.getQuantity() != null) {
            invoiceEntity.setGoodsNumber(entity.getQuantity().toString());
            invoiceEntity.setUnitPrice(BigDecimalUtils.divide(entity.getAmountWithoutTax(), entity.getQuantity()).toString());
        }
        invoiceEntity.setTaxRate(String.valueOf(entity.getTaxRate()));
        //从商品管理表中获取税收分类编码
        try {
            QueryWrapper<GoodsManageEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("project_code", projectCodeMax).eq("goods_name", entity.getPaymentName());
            invoiceEntity.setTaxCode(goodsManageService.getOne(queryWrapper).getTaxCode());
        } catch (Exception e) {
            log.error("税收分类编码查询异常：{}", e);
        }
        invoiceEntity.setCreateUserid(UserInfoUtil.getUserID());
        invoiceEntity.setGoodsSum(entity.getAmountWithoutTax().toString());
        invoiceEntity.setGoodTax(entity.getTaxAmount().toString());
        invoiceEntity.setGoodsSumTax(entity.getAmountWithTax().toString());
        invoiceEntity.setInvoiceRowNature("0");
        invoiceEntity.setTaxSign("0");
        invoiceEntity.setPreferentialMark("0");
        if (StrUtil.isBlank(entity.getTaxRateFlag())) {
            return null;
        }
        if (!"0".equals(entity.getTaxRateFlag())) {
            invoiceEntity.setTaxRateMark(entity.getTaxRateFlag());
        }
        return invoiceEntity;
    }

    /**
     * 合并发票明细
     *
     * @param detailList
     * @param goodsEntity
     * @return
     */
    private List<DocumentInfoDetailEntity> megerDetail(List<DocumentInfoDetailEntity> detailList, GoodsManageEntity goodsEntity) {
        List<DocumentInfoDetailEntity> list = new ArrayList<>();
        DocumentInfoDetailEntity newEntity = new DocumentInfoDetailEntity();
        DocumentInfoDetailEntity oldEntity = detailList.get(0);
        //总不含税金额
        double sumMoney = 0;
        double sumTaxAmount = 0;
        double sumAmountWithTax = 0;
        for (DocumentInfoDetailEntity detail : detailList) {
            sumMoney = BigDecimalUtils.add(sumMoney, detail.getAmountWithoutTax());
            sumTaxAmount = BigDecimalUtils.add(sumTaxAmount, Double.valueOf(detail.getTaxAmount()));
            sumAmountWithTax = BigDecimalUtils.add(sumAmountWithTax, Double.valueOf(detail.getAmountWithoutTax()));
        }
        newEntity.setDocId(oldEntity.getDocId());
        newEntity.setPaymentCategory(oldEntity.getPaymentCategory());
        newEntity.setPaymentType(oldEntity.getPaymentType());
        newEntity.setPaymentName(goodsEntity.getGoodsName());
        newEntity.setItemSpec(goodsEntity.getModel());
        newEntity.setQuantityUnit(goodsEntity.getUnit());
        newEntity.setQuantity(1.00);
        newEntity.setTaxRate(Double.valueOf(goodsEntity.getTaxRate()));
        newEntity.setUnitPriceOutTax(sumMoney);
        newEntity.setAmountWithoutTax(sumMoney);
        newEntity.setTaxAmount(String.valueOf(sumTaxAmount));
        newEntity.setAmountWithTax(sumAmountWithTax);
        newEntity.setTaxRateFlag(oldEntity.getTaxRateFlag());
        newEntity.setTenantId(oldEntity.getTenantId());
        list.add(newEntity);
        return list;
    }

    /**
     * 以款项名称合并发票明细
     *
     * @param detailList
     * @param projectCode
     * @return
     */
    private List<DocumentInfoDetailEntity> megerDetailByGoodsName(List<DocumentInfoDetailEntity> detailList, String projectCode) {
        //正则表达式 去除字符串结尾数字
        String pattern = "(\\d+)($)";
        List<String> oldStrList = new ArrayList<>();//明细行商品名称
        List<String> newStrList = new ArrayList<>();//明细行商品名称 去除结尾数字
        List<String> oldGoodsNaemList = new ArrayList<>();//明细行商品名称 去除结尾数字 分类汇总
        List<String> newGoodsNaemList = new ArrayList<>();//可合并的商品名称
        //拿到所有的goodsName 放入oldStrList
        detailList.stream().collect(Collectors.groupingBy(DocumentInfoDetailEntity::getPaymentName, Collectors.toList()))
                .forEach((paymentName, fooListByName) -> {
                    oldStrList.add(paymentName);
                });
        //去除goodsName结尾数字 放入newStrList
        oldStrList.stream().forEach((iteam) -> {
            newStrList.add(Pattern.compile(pattern).matcher(iteam).replaceAll(""));
        });
        //对newStrList分类汇总 放入oldGoodsNaemList
        newStrList.stream().collect(Collectors.groupingBy(String::length, Collectors.toList()))
                .forEach((i, iteam) -> {
                    oldGoodsNaemList.add(iteam.get(0));
                });
        if (CollectionUtil.isEmpty(oldGoodsNaemList)) {
            return null;
        }
        //查询出本项目所有可合并的goodsName  并且与oldGoodsNaemList中的比较 相同 则放入newGoodsNaemList
        QueryWrapper<GoodsManageEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("project_code", projectCode);
        List<GoodsManageEntity> listEntity = goodsManageService.list(queryWrapper);
        for (String goodsName : oldGoodsNaemList) {
            for (GoodsManageEntity entity : listEntity) {
                if (entity.getGoodsName().equals(goodsName)) {
                    newGoodsNaemList.add(goodsName);
                }
            }
        }
        if (CollectionUtil.isEmpty(newGoodsNaemList)) {
            return detailList;
        }
        //newGoodsNaemList与明细goodsName比较 相同则把明细goodsName重新赋值
        detailList.stream().forEach((iteam) -> {
            String paymentName = Pattern.compile(pattern).matcher(iteam.getPaymentName()).replaceAll("");
            for (String goodsName : newGoodsNaemList) {
                if (paymentName.equals(goodsName)) {
                    iteam.setPaymentName(goodsName);
                }
            }
        });
        //对明细分类汇总 并放入oldGroupList
        List<List<DocumentInfoDetailEntity>> oldGroupList = new ArrayList<>();
        detailList.stream().collect(Collectors.groupingBy(DocumentInfoDetailEntity::getPaymentName, Collectors.toList()))
                .forEach((paymentName, fooListByName) -> {
                            oldGroupList.add(fooListByName);
                        }
                );
        //对汇总之后的明细进行计算 并放入 newGroupList
        List<DocumentInfoDetailEntity> newGroupList = new ArrayList<>();
        for (List list : oldGroupList) {
            List<DocumentInfoDetailEntity> documentInfoList = (List<DocumentInfoDetailEntity>) list;
            //总不含税金额
            double sumMoney = 0;
            double sumTaxAmount = 0;
            double sumAmountWithTax = 0;
            for (DocumentInfoDetailEntity detail : documentInfoList) {
                sumMoney = BigDecimalUtils.add(sumMoney, detail.getAmountWithoutTax());
                sumTaxAmount = BigDecimalUtils.add(sumTaxAmount, Double.valueOf(detail.getTaxAmount()));
                sumAmountWithTax = BigDecimalUtils.add(sumAmountWithTax, Double.valueOf(detail.getAmountWithoutTax()));
            }
            DocumentInfoDetailEntity newDocumentInfoDetailEntity = documentInfoList.get(0);
            newDocumentInfoDetailEntity.setAmountWithoutTax(sumMoney);
            newDocumentInfoDetailEntity.setTaxAmount(String.valueOf(sumTaxAmount));
            newDocumentInfoDetailEntity.setAmountWithTax(sumAmountWithTax);
            newDocumentInfoDetailEntity.setQuantity(1.00);
            newDocumentInfoDetailEntity.setUnitPriceOutTax(sumMoney);
            newGroupList.add(newDocumentInfoDetailEntity);
        }
        return newGroupList;
    }

    /**
     * 已开发票导出
     *
     * @param request
     * @return
     */
    public void exportInvoiced(HttpServletRequest request, HttpServletResponse httpServletResponse) throws Exception {
        InvoicedDTO queryWrapper = queryWrapper(request);
        List<InvoicedExcelEntity> invoicedExcelEntities = baseMapper.selectInvoicExport(queryWrapper);
        for (InvoicedExcelEntity invoicedExcelEntity : invoicedExcelEntities) {
            invoicedExcelEntity.setInvoiceType(TransformationUtil.transInvoiceType(invoicedExcelEntity.getInvoiceType()));
            invoicedExcelEntity.setMakeInvoiceType(TransformationUtil.transMakeInvoiceType(invoicedExcelEntity.getMakeInvoiceType()));
            invoicedExcelEntity.setInvoiceState(TransformationUtil.transInvoiceState(invoicedExcelEntity.getInvoiceState()));
        }
        List<String> cols = ExcelDTO.invoicedCols;
        Map<String, String> map = MapUtil.of("sellerName", "公司名称");
        map.put("sellerTaxNo", "销方税号");
        map.put("purchaserName", "购方名称");
        map.put("purchaserTaxNo", "购方税号");
        map.put("orderNo", "结算单号");
        map.put("invoiceType", "发票类型");
        map.put("invoiceCode", "发票代码");
        map.put("invoiceNo", "发票号码");
        map.put("invoiceDate", "开票日期");
        map.put("totalSum", "合计金额");
        map.put("totalTax", "合计税额");
        map.put("invoiceState", "发票状态");
        map.put("oldInvoiceCode", "原发票号码");
        map.put("oldInvoiceNo", "原发票代码");
        map.put("drawer", "开票人");
        map.put("createUserid", "操作人");
        map.put("taxAuthority", "主管税务机关");
        map.put("taxAuthorityCode", "主管税务机关代码");
        map.put("sellerDepositBank", "销方开户银行");
        map.put("sellerAddress", "销方地址");
        map.put("sellerPhone", "销方电话");

        ExcelUtil.exportExcel(httpServletResponse, cols, map, invoicedExcelEntities, "已开发票管理");
    }

    /**
     * 已开发票明细导出
     *
     * @param request
     * @param httpServletResponse
     */
    public void exportDetail(HttpServletRequest request, HttpServletResponse httpServletResponse) throws Exception {
        InvoicedDTO queryWrapper = queryWrapper(request);
        List<InvoicedExcelEntity> invoicedExcelEntities = baseMapper.selectInvoiceDetailExport(queryWrapper);
        List<InvoiceDetailExcelEntity> invoiceDetailExcelEntities = new ArrayList<>();
        for (InvoicedExcelEntity sellerInvoiceEntity : invoicedExcelEntities) {
            String serialNo = sellerInvoiceEntity.getSerialNo();
            QueryWrapper<SellerInvoiceDetailEntity> detaiQuery = new QueryWrapper<>();
            detaiQuery.eq("serial_no", serialNo);
            detaiQuery.orderByDesc("create_time");
            List<SellerInvoiceDetailEntity> sellerInvoiceDetailEntities = invoiceDetailService.list(detaiQuery);
            for (SellerInvoiceDetailEntity sellerInvoiceDetailEntity : sellerInvoiceDetailEntities) {
                InvoiceDetailExcelEntity invoiceDetailExcelEntity = new InvoiceDetailExcelEntity();
                invoiceDetailExcelEntity.setSellerName(sellerInvoiceEntity.getSellerName());
                invoiceDetailExcelEntity.setSellerTaxNo(sellerInvoiceEntity.getSellerTaxNo());
                invoiceDetailExcelEntity.setPurchaserName(sellerInvoiceEntity.getPurchaserName());
                invoiceDetailExcelEntity.setPurchaserTaxNo(sellerInvoiceEntity.getPurchaserTaxNo());
                invoiceDetailExcelEntity.setInvoiceType(TransformationUtil.transInvoiceType(sellerInvoiceEntity.getInvoiceType()));
                invoiceDetailExcelEntity.setInvoiceCode(sellerInvoiceEntity.getInvoiceCode());
                invoiceDetailExcelEntity.setInvoiceNo(sellerInvoiceEntity.getInvoiceNo());
                invoiceDetailExcelEntity.setInvoiceDate(sellerInvoiceEntity.getInvoiceDate());
                invoiceDetailExcelEntity.setOrderNo(sellerInvoiceEntity.getOrderNo());
                invoiceDetailExcelEntity.setDrawer(sellerInvoiceEntity.getDrawer());
                invoiceDetailExcelEntity.setCreateUserId(sellerInvoiceEntity.getCreateUserid());
                invoiceDetailExcelEntity.setGoodsName(sellerInvoiceDetailEntity.getGoodsName());
                invoiceDetailExcelEntity.setModel(sellerInvoiceDetailEntity.getModel());
                invoiceDetailExcelEntity.setUnit(sellerInvoiceDetailEntity.getUnit());
                invoiceDetailExcelEntity.setUnitPrice(sellerInvoiceDetailEntity.getUnitPrice());
                invoiceDetailExcelEntity.setGoodsNumber(sellerInvoiceDetailEntity.getGoodsNumber());
                invoiceDetailExcelEntity.setGoodsSum(sellerInvoiceDetailEntity.getGoodsSum());
                invoiceDetailExcelEntity.setTaxRate(sellerInvoiceDetailEntity.getTaxRate());
                invoiceDetailExcelEntity.setGoodTax(sellerInvoiceDetailEntity.getGoodTax());
                invoiceDetailExcelEntities.add(invoiceDetailExcelEntity);
            }
        }
        List<String> cols = ExcelDTO.invoicedDetailCols;
        Map<String, String> map = MapUtil.of("sellerName", "公司名称");
        map.put("sellerTaxNo", "销方税号");
        map.put("purchaserName", "购方名称");
        map.put("purchaserTaxNo", "购方税号");
        map.put("invoiceType", "发票类型");
        map.put("invoiceCode", "发票代码");
        map.put("invoiceNo", "发票号码");
        map.put("invoiceDate", "开票日期");
        map.put("orderNo", "结算单号");
        map.put("goodsName", "商品名称");
        map.put("model", "规格型号");
        map.put("unit", "单位");
        map.put("unitPrice", "单价");
        map.put("goodsNumber", "数量");
        map.put("goodsSum", "不含税金额");
        map.put("taxRate", "税率");
        map.put("goodTax", "税额");
        map.put("drawer", "开票人");
        map.put("createUserId", "操作人");
        ExcelUtil.exportExcel(httpServletResponse, cols, map, invoiceDetailExcelEntities, "已开发票管理");
    }

    /**
     * 机动车已开发票明细导出
     *
     * @param request             条件
     * @param httpServletResponse
     */
    public void exportCarDetail(HttpServletRequest request, HttpServletResponse httpServletResponse) throws Exception {
        InvoicedDTO queryWrapper = queryWrapper(request);
        List<InvoicedExcelEntity> invoicedExcelEntities = baseMapper.selectInvoiceDetailExport(queryWrapper);
        List<InvoiceCarDetailExcelEntity> invoiceDetailExcelEntities = new ArrayList<>();
        for (InvoicedExcelEntity sellerInvoiceEntity : invoicedExcelEntities) {
            String serialNo = sellerInvoiceEntity.getSerialNo();
            QueryWrapper<SellerInvoiceDetailEntity> detaiQuery = new QueryWrapper<>();
            detaiQuery.eq("serial_no", serialNo);
            detaiQuery.orderByDesc("create_time");
            SellerInvoiceDetailEntity sellerInvoiceDetailEntitie = invoiceDetailService.getOne(detaiQuery);

            InvoiceCarDetailExcelEntity invoiceDetailExcelEntity = new InvoiceCarDetailExcelEntity();
            if(sellerInvoiceDetailEntitie!=null){
                BeanUtils.copyProperties(sellerInvoiceDetailEntitie,invoiceDetailExcelEntity);
                invoiceDetailExcelEntity.setGoodsName(sellerInvoiceDetailEntitie.getCarCategoryName());
            }
            invoiceDetailExcelEntity.setSellerName(sellerInvoiceEntity.getSellerName());
            invoiceDetailExcelEntity.setSellerTaxNo(sellerInvoiceEntity.getSellerTaxNo());
            invoiceDetailExcelEntity.setPurchaserName(sellerInvoiceEntity.getPurchaserName());
            invoiceDetailExcelEntity.setPurchaserTaxNo(sellerInvoiceEntity.getPurchaserTaxNo());
            invoiceDetailExcelEntity.setInvoiceType(TransformationUtil.transInvoiceType(sellerInvoiceEntity.getInvoiceType()));
            invoiceDetailExcelEntity.setInvoiceCode(sellerInvoiceEntity.getInvoiceCode());
            invoiceDetailExcelEntity.setInvoiceNo(sellerInvoiceEntity.getInvoiceNo());
            invoiceDetailExcelEntity.setInvoiceDate(sellerInvoiceEntity.getInvoiceDate());
            invoiceDetailExcelEntity.setOrderNo(sellerInvoiceEntity.getOrderNo());
            invoiceDetailExcelEntity.setDrawer(sellerInvoiceEntity.getDrawer());
            invoiceDetailExcelEntity.setCreateUserId(sellerInvoiceEntity.getCreateUserid());
            invoiceDetailExcelEntities.add(invoiceDetailExcelEntity);

        }
        List<String> cols = ExcelDTO.carInvoicedDetailCols;
        Map<String, String> map = MapUtil.of("sellerName", "公司名称");
        map.put("sellerTaxNo", "销方税号");
        map.put("purchaserName", "购方名称");
        map.put("purchaserTaxNo", "购方税号");
        map.put("invoiceType", "发票类型");
        map.put("invoiceCode", "发票代码");
        map.put("invoiceNo", "发票号码");
        map.put("invoiceDate", "开票日期");
        map.put("orderNo", "结算单号");
        map.put("goodsName", "商品名称");
        map.put("unit", "单位");
        map.put("unitPrice", "单价");
        map.put("goodsNumber", "数量");
        map.put("goodsSum", "不含税金额");
        map.put("taxRate", "税率");
        map.put("goodTax", "税额");
        map.put("brandMode", "厂牌型号");
        map.put("productionPlaceName", "产地");
        map.put("productionCompanyName", "生产企业名称");
        map.put("certificateNum", "合格证号");
        map.put("importTestimonialNum", "进口证明书号");
        map.put("engineNum", "发动机号码");
        map.put("carDiscernCode", "车辆识别代号/车架号码");
        map.put("tonnage", "吨位");
        map.put("maximumPeople", "限乘人数");
        map.put("inspectionOdd", "商检单号");
        map.put("drawer", "开票人");
        map.put("telephone", "电话");
        map.put("idCardNo", "身份证号码");
        map.put("taxOfName", "税务机关名称");
        map.put("taxOfCode", "税务机关代码");
        map.put("machinNo", "开票机号");
        map.put("createUserId", "操作人");


        ExcelUtil.exportExcel(httpServletResponse, cols, map, invoiceDetailExcelEntities, "已开发票管理");
    }


    //拼装查询条件
    private InvoicedDTO queryWrapper(HttpServletRequest request) {
        InvoicedDTO entity = new InvoicedDTO();
        if (StrUtil.isNotBlank(request.getParameter("invoiceType"))) {
            entity.setInvoiceType(request.getParameter("invoiceType"));
        }
        if (StrUtil.isNotBlank(request.getParameter("docId"))) {
            entity.setDocId(request.getParameter("docId"));
        }
        if (StrUtil.isNotBlank(request.getParameter("makeInvoiceType"))) {
            entity.setMakeInvoiceType(request.getParameter("makeInvoiceType"));
        }
        if (StrUtil.isNotBlank(request.getParameter("invoiceCode"))) {
            entity.setInvoiceCode(request.getParameter("invoiceCode"));
        }
        if (StrUtil.isNotBlank(request.getParameter("invoiceDateStart")) && StrUtil.isNotBlank(request.getParameter("invoiceDateEnd"))) {
            entity.setInvoiceDateStart(request.getParameter("invoiceDateStart"));
            entity.setInvoiceDateEnd(request.getParameter("invoiceDateEnd"));
        }
        if (StrUtil.isNotBlank(request.getParameter("dataSource"))) {
            entity.setDataSource(request.getParameter("data_source"));
        }
        if (StrUtil.isNotBlank(request.getParameter("invoiceNo"))) {
            entity.setInvoiceNo(request.getParameter("invoiceNo"));
        }
        if (StrUtil.isNotBlank(request.getParameter("oldInvoiceNo"))) {
            entity.setOldInvoiceNo(request.getParameter("oldInvoiceNo"));
        }
        if (StrUtil.isNotBlank(request.getParameter("purchaserName"))) {
            entity.setPurchaserName(request.getParameter("purchaserName"));
        }
        if (StrUtil.isNotBlank(request.getParameter("invoiceState"))) {
            entity.setInvoiceState(request.getParameter("invoiceState"));
        }
        if (StrUtil.isNotBlank(request.getParameter("purchaserTaxNo"))) {
            entity.setPurchaserTaxNo(request.getParameter("purchaserTaxNo"));
        }
        if (StrUtil.isBlank(request.getParameter("sellerTaxNo"))) {
            List<String> taxNos = commService.getTaxNumbers();
            entity.setSellerTaxNos(taxNos);
        } else {
            entity.setSellerTaxNo(request.getParameter("sellerTaxNo"));
        }
        if (StrUtil.isNotBlank(request.getParameter("projectMax"))) {
            entity.setProjectMax(request.getParameter("projectMax"));
        }
        if (StrUtil.isNotBlank(request.getParameter("room"))) {
            entity.setRoom(request.getParameter("room"));
        }
        if (StrUtil.isNotBlank(request.getParameter("taxRate"))) {
            entity.setTaxRate(request.getParameter("taxRate"));
        }
        return entity;
    }

    /**
     * 同步已开发票
     *
     * @param synchronizeInvoiceDTO
     * @return
     */
    public Response syncInvoice(SynchronizeInvoiceDTO synchronizeInvoiceDTO) {
        Response res = new Response();
        //获取开票设备
        String sellerTaxNo = synchronizeInvoiceDTO.getSellerTaxNo();
        EquipmentEntity equipmentEntity = equipmentService.getOne(new QueryWrapper<EquipmentEntity>().eq("seller_tax_no", sellerTaxNo).eq("disable", "1"));
        if (null == equipmentEntity) {
            res.setCode("T0001");
            res.setMsg("同步失败，该纳税人识别号对应的设备未添加或开启，请检查！");
            return res;
        }
        //设备类型
        String equipmentMode = equipmentEntity.getEquipmentMode();
        if (CodeConstant.A9.equals(equipmentMode)) {
            res = syncInvoiceA9(synchronizeInvoiceDTO);
        } else {
            res = syncInvoiceSST(synchronizeInvoiceDTO, equipmentEntity);
        }
        return res;
    }

    /**
     * A9服务器同步
     *
     * @return
     */
    private Response syncInvoiceA9(SynchronizeInvoiceDTO synchronizeInvoiceDTO) {
        String url = zzsfpUrl + "busiInterface";
        String interfaceCode = "EI.YKFPMXCX.U.EC.INTRA";
        String ykInvoiceData = FreemarkUtil.getTemplateObj("/commonYkfpmxcx.ftl", synchronizeInvoiceDTO);
        String xmlData = InvoiceHelper.getXmlData(ykInvoiceData, interfaceCode, synchronizeInvoiceDTO.getSellerTaxNo(), null);
        if (StrUtil.isBlank(xmlData)) {
            return Response.error("SEL_SYNC_004");
        }
        InterfaceDTO interfaceDTO = new InterfaceDTO();
        interfaceDTO.setXmlData(xmlData);
        interfaceDTO.setUrl(url);
        try {
            Response response = apiClientService.callSales(interfaceDTO);
            if (CodeConstant.T0000.equals(response.getCode())) {
                String reqcontent = response.getData().toString();
                Map<String, Object> resMap = Xml2Map.Xml2Mapz(reqcontent);
                List<Map> fp = new ArrayList<>();
                if ("".equals(resMap.get("FPXXS"))) {
                    return Response.error("同步发票信息为空");
                }
                Map<String, Map> fpxx = (Map<String, Map>) resMap.get("FPXXS");
                Object obj = fpxx.get("FPXX");
                if (obj instanceof List) {
                    fp = (List<Map>) fpxx.get("FPXX");
                } else if (obj instanceof Map) {
                    Map fpMap = fpxx.get("FPXX");
                    fp.add(fpMap);
                }
                this.dealSyncInvoiceA9(fp);
            } else {
                return Response.error(response.getCode(), response.getMsg());
            }
        } catch (Exception e) {
            log.info("报文解析失败", e);
            return Response.error("报文解析失败!请联系运维人员");
        }
        return Response.success();
    }

    //处理同步到的发票，存在更新，否则直接插入
    public void dealSyncInvoiceA9(List<Map> list) {
        List<SellerInvoiceEntity> sellerInvoiceEntities = new ArrayList<>();
        List<SellerInvoiceDetailEntity> sellerInvoiceDetailEntities = new ArrayList<>();
        SellerInvoiceEntity invoiceEntity = null;
        for (Map invoiceMapFP : list) {
            Map invoiceMap = (Map) invoiceMapFP.get("FP");
            String invoiceCode = MapUtils.getString(invoiceMap, "FPDM", "");
            String invoiceNo = MapUtils.getString(invoiceMap, "FPHM", "");
            QueryWrapper<SellerInvoiceEntity> invoiceQuery = new QueryWrapper<>();
            invoiceQuery.eq("invoice_code", invoiceCode);
            invoiceQuery.eq("invoice_no", invoiceNo);
            invoiceEntity = baseMapper.selectOne(invoiceQuery);
            if (invoiceEntity == null) {
                String taxRate = "";
                String serialNo = UUIDUitl.UUID32(false);
                SellerInvoiceEntity sellerInvoiceEntity = new SellerInvoiceEntity();
                sellerInvoiceEntity.setUuid(UUIDUitl.UUID32(false));
                sellerInvoiceEntity.setSerialNo(serialNo);
                String invoiceType = MapUtils.getString(invoiceMap, "FPZL_DM", "");
                invoiceType = TransformationUtil.transSstInvoiceType(invoiceType);
                sellerInvoiceEntity.setInvoiceType(invoiceType);
                String makeInvoiceType = MapUtils.getString(invoiceMap, "KPLX", "");
                //发票状态处理
                if (CodeConstant.BLUE_INVOICETYPE.equals(makeInvoiceType)) {
                    sellerInvoiceEntity.setMakeInvoiceType("0");
                    sellerInvoiceEntity.setInvoiceState("0");
                } else if (CodeConstant.RED_INVOICETYPE.equals(makeInvoiceType)) {
                    sellerInvoiceEntity.setMakeInvoiceType("1");
                    sellerInvoiceEntity.setInvoiceState("0");
                } else if (CodeConstant.DISCARD_BLUE_INVOICETYPE.equals(makeInvoiceType)) {
                    sellerInvoiceEntity.setMakeInvoiceType("0");
                    sellerInvoiceEntity.setInvoiceState("1");
                } else if (CodeConstant.DISCARD_RED_INVOICETYPE.equals(makeInvoiceType)) {
                    sellerInvoiceEntity.setMakeInvoiceType("1");
                    sellerInvoiceEntity.setInvoiceState("1");
                } else if (CodeConstant.DISCARD_BLANK_INVOICETYPE.equals(makeInvoiceType)) {
                    sellerInvoiceEntity.setInvoiceState("1");
                } else {
                    sellerInvoiceEntity.setMakeInvoiceType("0");
                    sellerInvoiceEntity.setInvoiceState("0");
                }
                sellerInvoiceEntity.setInvoiceCode(MapUtils.getString(invoiceMap, "FPDM", ""));
                sellerInvoiceEntity.setInvoiceNo(MapUtils.getString(invoiceMap, "FPHM", ""));
                sellerInvoiceEntity.setInvoiceDate(MapUtils.getString(invoiceMap, "KPSJ", ""));
                String kpsj = MapUtils.getString(invoiceMap, "KPSJ", "");
                if (StrUtil.isNotBlank(kpsj)) {
                    sellerInvoiceEntity.setInvoiceMonth(kpsj.substring(0, 7));
                    sellerInvoiceEntity.setInvoiceDate(DateUtil.getYYYYmmdd(kpsj));
                }
                sellerInvoiceEntity.setCipherText(MwDecryptUtil.desMw(MapUtils.getString(invoiceMap, "MW", "")));
                sellerInvoiceEntity.setPurchaserName(MapUtils.getString(invoiceMap, "GFMC", ""));
                sellerInvoiceEntity.setPurchaserTaxNo(MapUtils.getString(invoiceMap, "GFSH", ""));
                sellerInvoiceEntity.setPurchaserAddressTel(MapUtils.getString(invoiceMap, "GFDZDH", ""));
                sellerInvoiceEntity.setPurchaserBankAccount(MapUtils.getString(invoiceMap, "GFYHZH", ""));
                sellerInvoiceEntity.setSellerName(MapUtils.getString(invoiceMap, "XFMC", ""));
                sellerInvoiceEntity.setSellerTaxNo(MapUtils.getString(invoiceMap, "XFSH", ""));
                sellerInvoiceEntity.setSellerAddressTel(MapUtils.getString(invoiceMap, "XFDZDH", ""));
                sellerInvoiceEntity.setSellerBankAccount(MapUtils.getString(invoiceMap, "XFYHZH", ""));
                sellerInvoiceEntity.setTotalSum(MapUtils.getString(invoiceMap, "HJJE", ""));
                sellerInvoiceEntity.setTotalTax(MapUtils.getString(invoiceMap, "HJSE", ""));
                sellerInvoiceEntity.setTotalSumTax(MapUtils.getString(invoiceMap, "JSHJ", ""));
                sellerInvoiceEntity.setRemark(MapUtils.getString(invoiceMap, "BZ", ""));
                sellerInvoiceEntity.setPayee(MapUtils.getString(invoiceMap, "SKR", ""));
                sellerInvoiceEntity.setReviewer(MapUtils.getString(invoiceMap, "FHR", ""));
                sellerInvoiceEntity.setDrawer(MapUtils.getString(invoiceMap, "KPR", ""));
                sellerInvoiceEntity.setPanNo(MapUtils.getString(invoiceMap, "JSPBH", ""));
                sellerInvoiceEntity.setMakeInvoiceState("2");
                sellerInvoiceEntity.setPrintState("0");
                sellerInvoiceEntity.setDataSource("3");
                sellerInvoiceEntity.setOldInvoiceCode(MapUtils.getString(invoiceMap, "YFPDM", ""));
                sellerInvoiceEntity.setOldInvoiceNo(MapUtils.getString(invoiceMap, "YFPHM", ""));
                sellerInvoiceEntity.setCheckCode(MapUtils.getString(invoiceMap, "FWM", ""));
                sellerInvoiceEntity.setInvoiceUrl(MapUtils.getString(invoiceMap, "PDF_URL", ""));
                List<Map> invoiceDetailList = new ArrayList();
                Object obj = invoiceMap.get("MX");
                Map objMap = (Map) invoiceMap.get("MX");
                if (objMap.get("MXXX") instanceof List) {
                    invoiceDetailList = (List<Map>) objMap.get("MXXX");
                } else if (objMap instanceof Map) {
                    Map map = (Map) obj;
                    invoiceDetailList.add((Map) map.get("MXXX"));
                }
                for (int i = 0; i < invoiceDetailList.size(); i++) {
                    Map invoiceDetailMap = (Map) invoiceDetailList.get(i);
                    SellerInvoiceDetailEntity sellerInvoiceDetailEntity = new SellerInvoiceDetailEntity();
                    sellerInvoiceDetailEntity.setUuid(UUIDUitl.UUID32(false));
                    sellerInvoiceDetailEntity.setSerialNo(serialNo);
                    sellerInvoiceDetailEntity.setGoodsName(MapUtils.getString(invoiceDetailMap, "XMMC", ""));
                    sellerInvoiceDetailEntity.setModel(MapUtils.getString(invoiceDetailMap, "GGXH", ""));
                    sellerInvoiceDetailEntity.setUnit(MapUtils.getString(invoiceDetailMap, "JXDW", ""));
                    sellerInvoiceDetailEntity.setGoodsNumber(MapUtils.getString(invoiceDetailMap, "XMSL", ""));
                    sellerInvoiceDetailEntity.setUnitPrice(MapUtils.getString(invoiceDetailMap, "BHSDJ", ""));
                    String goodSum = MapUtils.getString(invoiceDetailMap, "XMJE", "0");
                    sellerInvoiceDetailEntity.setGoodsSum(goodSum);
                    String slv = MapUtils.getString(invoiceDetailMap, "SL", "");
                    if (InvoiceImgUtil.isSpecialChar(slv)) {
                        String slvNew = slv.replaceAll("%", "");
                        if (Double.valueOf(slvNew) == 10) {
                            slv = "0.1";
                        } else if (Double.valueOf(slvNew) < 10) {
                            slv = "0.0" + slvNew;
                        } else if (Double.valueOf(slvNew) > 10) {
                            slv = "0." + slvNew;
                        }
                    }
                    taxRate = slv;
                    sellerInvoiceDetailEntity.setTaxRate(slv);
                    String goodTax = MapUtils.getString(invoiceDetailMap, "SE", "");
                    sellerInvoiceDetailEntity.setGoodTax(goodTax);
                    sellerInvoiceDetailEntity.setGoodsSumTax(MapUtils.getString(invoiceDetailMap, "HSJE", "0"));
                    sellerInvoiceDetailEntity.setTaxRateMark(MapUtils.getString(invoiceDetailMap, "LSLBS", ""));
                    sellerInvoiceDetailEntity.setPreferentialMark(MapUtils.getString(invoiceDetailMap, "YHZCBS", ""));
                    sellerInvoiceDetailEntity.setPreferentialName(MapUtils.getString(invoiceDetailMap, "ZZSTSGL", ""));
                    sellerInvoiceDetailEntity.setTaxCode(MapUtils.getString(invoiceDetailMap, "SPBM", ""));
                    sellerInvoiceDetailEntity.setInvoiceRowNature(MapUtils.getString(invoiceDetailMap, "FPHXZ", ""));
                    sellerInvoiceDetailEntity.setDetailNo(MapUtils.getString(invoiceDetailMap, "ZXBM", ""));
                    sellerInvoiceDetailEntities.add(sellerInvoiceDetailEntity);
                }
                sellerInvoiceEntity.setTaxRate(taxRate);
                sellerInvoiceEntities.add(sellerInvoiceEntity);
            } else {
                //同步的发票状态 1.蓝票 2.红票 3.空白废 4.蓝废 5.红废
                String makeInvoiceType = MapUtils.getString(invoiceMap, "KPLX", "");
                //发票状态处理
                if (Arrays.asList("3", "4", "5").contains(makeInvoiceType)) {
                    invoiceEntity.setInvoiceState("1");
                }
                baseMapper.update(invoiceEntity, new QueryWrapper<SellerInvoiceEntity>().eq("serial_no", invoiceEntity.getSerialNo()));
            }
        }
        if (sellerInvoiceEntities != null && !sellerInvoiceEntities.isEmpty()) {
            this.saveBatch(sellerInvoiceEntities);
        }
        if (sellerInvoiceDetailEntities != null && !sellerInvoiceDetailEntities.isEmpty()) {
            invoiceDetailService.saveBatch(sellerInvoiceDetailEntities);
        }
    }

    /**
     * 税神通发票同步
     *
     * @return
     */
    private Response syncInvoiceSST(SynchronizeInvoiceDTO synchronizeInvoiceDTO, EquipmentEntity equipmentEntity) {
        Response res = new Response();
        String appid = equipmentEntity.getAppid();
        String equipmentMode = equipmentEntity.getEquipmentMode();
        String invoiceDateStart = synchronizeInvoiceDTO.getInvoiceDateStart();
        String invoiceDateEnd = synchronizeInvoiceDTO.getInvoiceDateEnd();
        String invoiceDate = synchronizeInvoiceDTO.getInvoiceDate();
        String dateStart = null;
        String dateEnd = null;
        if (invoiceDateStart != null || "".equals(invoiceDateStart)) {
            dateStart = DateUtil.transDate(invoiceDateStart);
        }
        if (invoiceDateEnd != null || "".equals(invoiceDateEnd)) {
            dateEnd = DateUtil.transDate(invoiceDateEnd);
        }
        String sellerTaxNo = synchronizeInvoiceDTO.getSellerTaxNo();
        List<String> invoiceTypes = null;
        if (CodeConstant.JSP.equals(equipmentMode)){
            // 金税盘同步到的发票为全部发票，不需要传发票类型
            invoiceTypes = Arrays.asList(CodeConstant.JSP);
        } else {
//            invoiceTypes = synchronizeInvoiceDTO.getInvoiceTypeList();
            invoiceTypes = Arrays.asList(equipmentEntity.getInvoiceTypeList().split(","));
        }

        StringBuilder msgs = new StringBuilder();
        for (String invoiceType : invoiceTypes) {
            String json = null;
            if (equipmentMode.equals(CodeConstant.JSP)) {
                json = IntJsonUtil.syncInvoice(equipmentMode, appid, dateStart, dateEnd, sellerTaxNo, invoiceType, invoiceDate);
            } else {
                json = IntJsonUtil.syncInvoice(equipmentMode, appid, dateStart, dateEnd, sellerTaxNo, invoiceType, null);
            }
            SellerInvoiceDTO sellerInvoiceDTO = new SellerInvoiceDTO();
            sellerInvoiceDTO.setBw(json);
            Response response = apiClientService.callSST(sellerInvoiceDTO);
            String result = (String) response.getData();
            JSONObject jsonObject = (JSONObject) JSON.parse(result);
            String code = jsonObject.getString("code");
            String msg = jsonObject.getString("msg");
            SyncInvoiceDTO syncInvoiceDTO = new SyncInvoiceDTO();
            syncInvoiceDTO.setSellerTaxNo(synchronizeInvoiceDTO.getSellerTaxNo());
            syncInvoiceDTO.setSellerName(synchronizeInvoiceDTO.getSellerName());
            syncInvoiceDTO.setEquipmentMode(equipmentMode);
            if (CodeConstant.THIRD_PARTY_SUCCESS.equals(code)) {
                List resList = (List) jsonObject.get("data");
                if(CodeConstant.INVOICETYPE_JDC.equals(invoiceType)){
                    updateSellerCarInvoiceInfoSST(resList, syncInvoiceDTO);
                }else {
                    updateSellerInvoiceInfoSST(resList, syncInvoiceDTO);
                }
//                msgs.append(TransformationUtil.transInvoiceType(invoiceType)+msg+",");
            } else {
                if (!msg.contains("09d106")) {
                    msgs.append(TransformationUtil.transInvoiceType(invoiceType) + msg + ",");
                }
            }
        }
        if (!StringUtil.isEmpty(msgs)){
            return Response.error(CodeConstant.T0001,msgs.toString());
        }
        return Response.success();
    }


    /**
     * 税神通发票处理
     *
     * @param invoiceList
     * @param syncInvoiceDTO
     */
    public void updateSellerInvoiceInfoSST(List<Map> invoiceList, SyncInvoiceDTO syncInvoiceDTO) {
        String equipmentMode = syncInvoiceDTO.getEquipmentMode();
        String sellerName = syncInvoiceDTO.getSellerName();
        String sellerTaxNo = syncInvoiceDTO.getSellerTaxNo();
        List<SellerInvoiceEntity> sellerInvoiceEntityList = new ArrayList<SellerInvoiceEntity>();
        List<SellerInvoiceDetailEntity> sellerInvoiceDetailEntityList = new ArrayList<SellerInvoiceDetailEntity>();
        for (Map invoiceMap : invoiceList) {
            String invoiceCode = MapUtils.getString(invoiceMap, "fpdm", "");
            String invoiceNo = MapUtils.getString(invoiceMap, "fphm", "");
            QueryWrapper<SellerInvoiceEntity> invoiceQuery = new QueryWrapper<>();
            invoiceQuery.eq("invoice_code", invoiceCode);
            invoiceQuery.eq("invoice_no", invoiceNo);
            SellerInvoiceEntity sellerInvoiceEntity = baseMapper.selectOne(invoiceQuery);
            if (sellerInvoiceEntity == null) {
                String taxRate = "";
                String serialNo = UUIDUitl.UUID32();
                SellerInvoiceEntity newSelInvoiceEntity = new SellerInvoiceEntity();
                newSelInvoiceEntity.setUuid(UUIDUitl.UUID32());
                newSelInvoiceEntity.setSerialNo(serialNo);
                String fplxdm = MapUtils.getString(invoiceMap, "fplxdm", "");
                if (equipmentMode.equals(CodeConstant.EQUIPMENT_JSP)) {
                    fplxdm = PrinterConstant.transInvoiceType(fplxdm);
                }
                newSelInvoiceEntity.setInvoiceType(fplxdm);
                String totalSum = MapUtils.getString(invoiceMap, "hjje", "");
                double totalSumDouble = Double.valueOf(totalSum);
                String makeInvoiceType = "0";
                if (totalSumDouble < 0) {
                    makeInvoiceType = "1";
                }
                newSelInvoiceEntity.setMakeInvoiceType(makeInvoiceType);
                newSelInvoiceEntity.setInvoiceCode(MapUtils.getString(invoiceMap, "fpdm", ""));
                newSelInvoiceEntity.setInvoiceNo(MapUtils.getString(invoiceMap, "fphm", ""));
                String invoiceDate = MapUtils.getString(invoiceMap, "kprq", "");
                //开票日期同意格式化为yyyy-MM-dd格式
                newSelInvoiceEntity.setInvoiceDate(DateUtil.getFormatDateTime(invoiceDate));
                newSelInvoiceEntity.setCipherText(MapUtils.getString(invoiceMap, "mw", ""));
                newSelInvoiceEntity.setPurchaserName(MapUtils.getString(invoiceMap, "ghdwmc", ""));
                newSelInvoiceEntity.setPurchaserTaxNo(MapUtils.getString(invoiceMap, "ghdwsbh", ""));
                newSelInvoiceEntity.setPurchaserAddressTel(MapUtils.getString(invoiceMap, "ghdwdzdh", ""));
                newSelInvoiceEntity.setPurchaserBankAccount(MapUtils.getString(invoiceMap, "ghdwyhzh", ""));
                newSelInvoiceEntity.setSellerName(sellerName);
                newSelInvoiceEntity.setSellerTaxNo(sellerTaxNo);
                newSelInvoiceEntity.setSellerAddressTel(MapUtils.getString(invoiceMap, "xhdwdzdh", ""));
                newSelInvoiceEntity.setSellerBankAccount(MapUtils.getString(invoiceMap, "xhdwyhzh", ""));
                newSelInvoiceEntity.setTotalSum(MapUtils.getString(invoiceMap, "hjje", ""));
                newSelInvoiceEntity.setTotalTax(MapUtils.getString(invoiceMap, "hjse", ""));
                newSelInvoiceEntity.setTotalSumTax(MapUtils.getString(invoiceMap, "jshj", ""));
                newSelInvoiceEntity.setRemark(MapUtils.getString(invoiceMap, "bz", ""));
                newSelInvoiceEntity.setPayee(MapUtils.getString(invoiceMap, "skr", ""));
                newSelInvoiceEntity.setReviewer(MapUtils.getString(invoiceMap, "fhr", ""));
                newSelInvoiceEntity.setDrawer(MapUtils.getString(invoiceMap, "kpr", ""));
                newSelInvoiceEntity.setOldInvoiceCode(MapUtils.getString(invoiceMap, "yfpdm", ""));
                newSelInvoiceEntity.setOldInvoiceNo(MapUtils.getString(invoiceMap, "yfphm", ""));
                newSelInvoiceEntity.setInvoiceUrl(MapUtils.getString(invoiceMap, "pdf_url", ""));
                newSelInvoiceEntity.setMailBox(MapUtils.getString(invoiceMap, "gmf_dzyx", ""));
                if (StrUtil.isNotBlank(invoiceDate)){
                    newSelInvoiceEntity.setInvoiceMonth(DateUtil.getFormatDateTime(invoiceDate).substring(0,7));
                    newSelInvoiceEntity.setInvoiceDay(DateUtil.getFormatDateTime(invoiceDate));
                }
                String invoiceState = MapUtils.getString(invoiceMap, "fpzt", "");
                if (invoiceState.equals("0") || invoiceState.equals("1")) {
                    newSelInvoiceEntity.setInvoiceState("0");
                } else if (invoiceState.equals("3") || invoiceState.equals("4") || invoiceState.equals("2")) {
                    newSelInvoiceEntity.setInvoiceState("1");
                }

                newSelInvoiceEntity.setMakeInvoiceState("2");
                newSelInvoiceEntity.setPrintState("0");
                newSelInvoiceEntity.setDataSource("3");  //数据同步
                newSelInvoiceEntity.setCheckCode(MapUtils.getString(invoiceMap, "jym", ""));
                List invoiceDetailList = (List) MapUtils.getObject(invoiceMap, "mx", new ArrayList());
                int invoiceDetailListSize = invoiceDetailList.size();
                int size = invoiceDetailList.size();
                if (size <= 8) {
                    newSelInvoiceEntity.setListFlag(CodeConstant.COMM_CODE_0);
                } else {
                    newSelInvoiceEntity.setListFlag(CodeConstant.COMM_CODE_1);
                }
                int invoiceSort = 0;
                for (int j = 0; j < invoiceDetailListSize; j++) {
                    invoiceSort++;
                    Map invoiceDetailMap = (Map) invoiceDetailList.get(j);
                    SellerInvoiceDetailEntity sellerInvoiceDetailEntity = new SellerInvoiceDetailEntity();
                    sellerInvoiceDetailEntity.setUuid(UUIDUitl.UUID32());
                    sellerInvoiceDetailEntity.setSerialNo(serialNo);
                    sellerInvoiceDetailEntity.setGoodsName(MapUtils.getString(invoiceDetailMap, "spmc", ""));
                    sellerInvoiceDetailEntity.setModel(MapUtils.getString(invoiceDetailMap, "ggxh", ""));
                    sellerInvoiceDetailEntity.setUnit(MapUtils.getString(invoiceDetailMap, "dw", ""));
                    sellerInvoiceDetailEntity.setUnitPrice(MapUtils.getString(invoiceDetailMap, "dj", ""));
                    sellerInvoiceDetailEntity.setGoodsNumber(MapUtils.getString(invoiceDetailMap, "spsl", ""));
                    String goodSum = MapUtils.getString(invoiceDetailMap, "je", "0");
                    sellerInvoiceDetailEntity.setGoodsSum(goodSum);
                    String slv = MapUtils.getString(invoiceDetailMap, "sl", "");
                    if (InvoiceImgUtil.isSpecialChar(slv)) {
                        String slvNew = slv.replaceAll("%", "");
                        if (Double.valueOf(slvNew) == 10) {
                            slv = "0.1";
                        }
                        if (Double.valueOf(slvNew) < 10) {
                            slv = "0.0" + slvNew;
                        } else if (Double.valueOf(slvNew) > 10) {
                            slv = "0." + slvNew;
                        }
                    }
                    taxRate = slv;
                    sellerInvoiceDetailEntity.setTaxRate(slv);
                    String goodTax = MapUtils.getString(invoiceDetailMap, "se", "0");
                    sellerInvoiceDetailEntity.setGoodTax(goodTax);
                    sellerInvoiceDetailEntity.setTaxRateMark(MapUtils.getString(invoiceDetailMap, "slbs", ""));
                    sellerInvoiceDetailEntity.setPreferentialMark(MapUtils.getString(invoiceDetailMap, "yhzcbs", ""));
                    sellerInvoiceDetailEntity.setPreferentialName(MapUtils.getString(invoiceDetailMap, "zzstsgl", ""));
                    sellerInvoiceDetailEntity.setTaxCode(MapUtils.getString(invoiceDetailMap, "spbm", ""));
                    sellerInvoiceDetailEntity.setInvoiceRowNature(MapUtils.getString(invoiceDetailMap, "fphxz", ""));
                    sellerInvoiceDetailEntity.setDetailNo(MapUtils.getString(invoiceDetailMap, "xh", ""));
                    sellerInvoiceDetailEntity.setGoodsSumTax(String.valueOf(Arith.add(Double.valueOf(goodSum), Double.valueOf(goodTax))));
                    sellerInvoiceDetailEntity.setRedMark("0");
                    sellerInvoiceDetailEntity.setInvoiceSort(invoiceSort);
                    sellerInvoiceDetailEntityList.add(sellerInvoiceDetailEntity);
                }
                newSelInvoiceEntity.setTaxRate(taxRate);
                sellerInvoiceEntityList.add(newSelInvoiceEntity);
            } else {
                String state = MapUtils.getString(invoiceMap, "fpzt", "0");
                String updateState = sellerInvoiceEntity.getInvoiceState();
                if ("2".equals(sellerInvoiceEntity.getInvoiceState())) {
                    updateState = "2";
                } else if (state.equals("0") || state.equals("1")) {
                    updateState = "0";
                } else if (state.equals("3") || state.equals("4") || state.equals("2")) {
                    updateState = "1";
                }
                sellerInvoiceEntity.setInvoiceState(updateState);
                sellerInvoiceEntity.setCipherText(MapUtils.getString(invoiceMap, "mw", ""));
                baseMapper.update(sellerInvoiceEntity, new QueryWrapper<SellerInvoiceEntity>().eq("serial_no", sellerInvoiceEntity.getSerialNo()));
            }
        }
        if (sellerInvoiceEntityList != null && !sellerInvoiceEntityList.isEmpty()) {
            this.saveBatch(sellerInvoiceEntityList);
        }
        if (sellerInvoiceDetailEntityList != null && !sellerInvoiceDetailEntityList.isEmpty()) {
            invoiceDetailService.saveBatch(sellerInvoiceDetailEntityList);
        }
    }

    /**
     * 税神通发票处理
     *
     * @param invoiceList
     * @param syncInvoiceDTO
     */
    public void updateSellerCarInvoiceInfoSST(List<Map> invoiceList, SyncInvoiceDTO syncInvoiceDTO) {
        String equipmentMode = syncInvoiceDTO.getEquipmentMode();
        String sellerName = syncInvoiceDTO.getSellerName();
        String sellerTaxNo = syncInvoiceDTO.getSellerTaxNo();
        List<SellerInvoiceEntity> sellerInvoiceEntityList = new ArrayList<SellerInvoiceEntity>();
        List<SellerInvoiceDetailEntity> sellerInvoiceDetailEntityList = new ArrayList<SellerInvoiceDetailEntity>();
        for (Map invoiceMap : invoiceList) {
            String invoiceCode = MapUtils.getString(invoiceMap, "fpdm", "");
            String invoiceNo = MapUtils.getString(invoiceMap, "fphm", "");
            QueryWrapper<SellerInvoiceEntity> invoiceQuery = new QueryWrapper<>();
            invoiceQuery.eq("invoice_code", invoiceCode);
            invoiceQuery.eq("invoice_no", invoiceNo);
            SellerInvoiceEntity sellerInvoiceEntity = baseMapper.selectOne(invoiceQuery);
            if (sellerInvoiceEntity == null) {
                String taxRate = "";
                String serialNo = UUIDUitl.UUID32();
                SellerInvoiceEntity newSelInvoiceEntity = new SellerInvoiceEntity();
                newSelInvoiceEntity.setUuid(UUIDUitl.UUID32());
                newSelInvoiceEntity.setSerialNo(serialNo);
                String fplxdm = MapUtils.getString(invoiceMap, "fplxdm", "");
                if (equipmentMode.equals(CodeConstant.EQUIPMENT_JSP)) {
                    fplxdm = PrinterConstant.transInvoiceType(fplxdm);
                }
                newSelInvoiceEntity.setInvoiceType(fplxdm);
                String totalSum = MapUtils.getString(invoiceMap, "jshj", "");
                double totalSumDouble = Double.valueOf(totalSum);
                String makeInvoiceType = "0";
                if (totalSumDouble < 0) {
                    makeInvoiceType = "1";
                }
                newSelInvoiceEntity.setMakeInvoiceType(makeInvoiceType);
                newSelInvoiceEntity.setInvoiceCode(MapUtils.getString(invoiceMap, "fpdm", ""));
                newSelInvoiceEntity.setInvoiceNo(MapUtils.getString(invoiceMap, "fphm", ""));
                String invoiceDate = MapUtils.getString(invoiceMap, "kprq", "");
                //开票日期同意格式化为yyyy-MM-dd格式
                newSelInvoiceEntity.setInvoiceDate(DateUtil.getFormatDateTime(invoiceDate));
                newSelInvoiceEntity.setCipherText(MapUtils.getString(invoiceMap, "mw", ""));
                newSelInvoiceEntity.setPurchaserName(MapUtils.getString(invoiceMap, "ghdwmc", ""));
                newSelInvoiceEntity.setPurchaserTaxNo(MapUtils.getString(invoiceMap, "ghdwsbh", ""));
                newSelInvoiceEntity.setPurchaserAddressTel(MapUtils.getString(invoiceMap, "ghdwdzdh", ""));
                newSelInvoiceEntity.setPurchaserBankAccount(MapUtils.getString(invoiceMap, "ghdwyhzh", ""));
                newSelInvoiceEntity.setSellerName(sellerName);
                newSelInvoiceEntity.setSellerTaxNo(sellerTaxNo);
                newSelInvoiceEntity.setSellerAddressTel(MapUtils.getString(invoiceMap, "xhdwdzdh", ""));
                newSelInvoiceEntity.setSellerBankAccount(MapUtils.getString(invoiceMap, "xhdwyhzh", ""));
                newSelInvoiceEntity.setTotalSum(MapUtils.getString(invoiceMap, "bhsj", ""));
                newSelInvoiceEntity.setTotalTax(MapUtils.getString(invoiceMap, "hjse", ""));
                newSelInvoiceEntity.setTotalSumTax(MapUtils.getString(invoiceMap, "jshj", ""));
                newSelInvoiceEntity.setRemark(MapUtils.getString(invoiceMap, "bz", ""));
                newSelInvoiceEntity.setPayee(MapUtils.getString(invoiceMap, "skr", ""));
                newSelInvoiceEntity.setReviewer(MapUtils.getString(invoiceMap, "fhr", ""));
                newSelInvoiceEntity.setDrawer(MapUtils.getString(invoiceMap, "kpr", ""));
                newSelInvoiceEntity.setOldInvoiceCode(MapUtils.getString(invoiceMap, "yfpdm", ""));
                newSelInvoiceEntity.setOldInvoiceNo(MapUtils.getString(invoiceMap, "yfphm", ""));
                newSelInvoiceEntity.setInvoiceUrl(MapUtils.getString(invoiceMap, "pdf_url", ""));
                newSelInvoiceEntity.setMailBox(MapUtils.getString(invoiceMap, "gmf_dzyx", ""));
                newSelInvoiceEntity.setTaxVoucherNo(MapUtils.getString(invoiceMap,"wspzhm",""));
                if (StrUtil.isNotBlank(invoiceDate)){
                    newSelInvoiceEntity.setInvoiceMonth(DateUtil.getFormatDateTime(invoiceDate).substring(0,7));
                    newSelInvoiceEntity.setInvoiceDay(DateUtil.getFormatDateTime(invoiceDate));
                }
                String invoiceState = MapUtils.getString(invoiceMap, "fpzt", "");
                if (invoiceState.equals("0") || invoiceState.equals("1")) {
                    newSelInvoiceEntity.setInvoiceState("0");
                } else if (invoiceState.equals("3") || invoiceState.equals("4") || invoiceState.equals("2")) {
                    newSelInvoiceEntity.setInvoiceState("1");
                }

                newSelInvoiceEntity.setMakeInvoiceState("2");
                newSelInvoiceEntity.setPrintState("0");
                newSelInvoiceEntity.setDataSource("3");  //数据同步
                newSelInvoiceEntity.setCheckCode(MapUtils.getString(invoiceMap, "jym", ""));
                List invoiceDetailList = (List) MapUtils.getObject(invoiceMap, "mx", new ArrayList());
                int invoiceDetailListSize = invoiceDetailList.size();
                int invoiceSort = 0;
                SellerInvoiceDetailEntity sellerInvoiceDetailEntity = new SellerInvoiceDetailEntity();
                sellerInvoiceDetailEntity.setUuid(UUIDUitl.UUID32());
                sellerInvoiceDetailEntity.setSerialNo(serialNo);
                sellerInvoiceDetailEntity.setGoodsName(MapUtils.getString(invoiceMap, "spmc", ""));
                sellerInvoiceDetailEntity.setModel(MapUtils.getString(invoiceMap, "ggxh", ""));
                sellerInvoiceDetailEntity.setUnit(MapUtils.getString(invoiceMap, "dw", ""));
                sellerInvoiceDetailEntity.setUnitPrice(MapUtils.getString(invoiceMap, "dj", ""));
                sellerInvoiceDetailEntity.setGoodsNumber(MapUtils.getString(invoiceMap, "spsl", ""));
                String goodSum = MapUtils.getString(invoiceMap, "je", "0");
                sellerInvoiceDetailEntity.setGoodsSum(goodSum);
                String slv = MapUtils.getString(invoiceMap, "sl", "");
                if (InvoiceImgUtil.isSpecialChar(slv)) {
                    String slvNew = slv.replaceAll("%", "");
                    if (Double.valueOf(slvNew) == 10) {
                        slv = "0.1";
                    }
                    if (Double.valueOf(slvNew) < 10) {
                        slv = "0.0" + slvNew;
                    } else if (Double.valueOf(slvNew) > 10) {
                        slv = "0." + slvNew;
                    }
                }
                taxRate = slv;
                sellerInvoiceDetailEntity.setTaxRate(slv);
                String goodTax = MapUtils.getString(invoiceMap, "se", "0");
                sellerInvoiceDetailEntity.setGoodTax(goodTax);
                sellerInvoiceDetailEntity.setTaxRateMark(MapUtils.getString(invoiceMap, "slbs", ""));
                sellerInvoiceDetailEntity.setPreferentialMark(MapUtils.getString(invoiceMap, "yhzcbs", ""));
                sellerInvoiceDetailEntity.setPreferentialName(MapUtils.getString(invoiceMap, "zzstsgl", ""));
//                sellerInvoiceDetailEntity.setTaxCode(MapUtils.getString(invoiceMap, "spbm", ""));
//                sellerInvoiceDetailEntity.setInvoiceRowNature(MapUtils.getString(invoiceMap, "fphxz", ""));
                sellerInvoiceDetailEntity.setGoodsSumTax(String.valueOf(Arith.add(Double.valueOf(goodSum), Double.valueOf(goodTax))));
                sellerInvoiceDetailEntity.setRedMark("0");
                sellerInvoiceDetailEntity.setInvoiceSort(invoiceSort);
                sellerInvoiceDetailEntity.setTelephone(MapUtils.getString(invoiceMap,"dh",""));
                sellerInvoiceDetailEntity.setIdCardNo(MapUtils.getString(invoiceMap,"sfzhm",""));
                sellerInvoiceDetailEntity.setTaxOfName(MapUtils.getString(invoiceMap,"swjgmc",""));
                sellerInvoiceDetailEntity.setTaxOfCode(MapUtils.getString(invoiceMap,"swjgdm",""));
                sellerInvoiceDetailEntity.setMachinNo(MapUtils.getString(invoiceMap,"kpjh",""));
                sellerInvoiceDetailEntity.setCarCategoryName(MapUtils.getString(invoiceMap,"cllx",""));
                sellerInvoiceDetailEntity.setBrandMode(MapUtils.getString(invoiceMap,"cpxh",""));
                sellerInvoiceDetailEntity.setProductionCompanyName(MapUtils.getString(invoiceMap,"scqymc",""));
                sellerInvoiceDetailEntity.setCertificateNum(MapUtils.getString(invoiceMap,"hgzh",""));
                sellerInvoiceDetailEntity.setImportTestimonialNum(MapUtils.getString(invoiceMap,"jkzmsh",""));
                sellerInvoiceDetailEntity.setEngineNum(MapUtils.getString(invoiceMap,"fdjhm",""));
                sellerInvoiceDetailEntity.setCarDiscernCode(MapUtils.getString(invoiceMap,"cjhm",""));
                sellerInvoiceDetailEntity.setTonnage(MapUtils.getString(invoiceMap,"dw",""));
                sellerInvoiceDetailEntity.setMaximumPeople(MapUtils.getString(invoiceMap,"xcrs",""));
                sellerInvoiceDetailEntity.setInspectionOdd(MapUtils.getString(invoiceMap,"sjdh",""));
                sellerInvoiceDetailEntity.setProductionPlaceName(MapUtils.getString(invoiceMap,"cd",""));
                sellerInvoiceDetailEntityList.add(sellerInvoiceDetailEntity);
                newSelInvoiceEntity.setTaxRate(taxRate);
                sellerInvoiceEntityList.add(newSelInvoiceEntity);
            } else {
                String state = MapUtils.getString(invoiceMap, "fpzt", "0");
                String updateState = sellerInvoiceEntity.getInvoiceState();
                if ("2".equals(sellerInvoiceEntity.getInvoiceState())) {
                    updateState = "2";
                } else if (state.equals("0") || state.equals("1")) {
                    updateState = "0";
                } else if (state.equals("3") || state.equals("4") || state.equals("2")) {
                    updateState = "1";
                }
                sellerInvoiceEntity.setInvoiceState(updateState);
                sellerInvoiceEntity.setCipherText(MapUtils.getString(invoiceMap, "mw", ""));
                baseMapper.update(sellerInvoiceEntity, new QueryWrapper<SellerInvoiceEntity>().eq("serial_no", sellerInvoiceEntity.getSerialNo()));
            }
        }
        if (sellerInvoiceEntityList != null && !sellerInvoiceEntityList.isEmpty()) {
            this.saveBatch(sellerInvoiceEntityList);
        }
        if (sellerInvoiceDetailEntityList != null && !sellerInvoiceDetailEntityList.isEmpty()) {
            invoiceDetailService.saveBatch(sellerInvoiceDetailEntityList);
        }
    }

    /**
     * 发票作废
     *
     * @param invoicedDTO
     * @return
     */
    public Response invoiceCancel(InvoicedDTO invoicedDTO) throws UnsupportedEncodingException {
        Response response = new Response();
        List<String> serialNos = invoicedDTO.getSerialNos();
        for (String serialNo : serialNos) {
            QueryWrapper<SellerInvoiceEntity> querySeller = new QueryWrapper<>();
            querySeller.eq("serial_no", serialNos.get(0));
            SellerInvoiceEntity invoiceEntity = baseMapper.selectOne(querySeller);
            if (("005".equals(invoiceEntity.getInvoiceType())) && !"1".equals(invoiceEntity.getMakeInvoiceType())) {
                return Response.error(CodeConstant.T0001, "机动车发票只支持红票作废!");
            }
            if (("12".equals(invoiceEntity.getInvoiceType()))) {
                return Response.error(CodeConstant.T0001, "机动车专票不能作废!");
            }
            //判断该税号下设备是否开启
            EquipmentEntity equipmentEntity = equipmentService.queryEquipment(invoiceEntity.getSellerTaxNo());
            if (equipmentEntity == null || CodeConstant.COMM_CODE_0.equals(equipmentEntity.getDisable())) {
                return Response.error(CodeConstant.ERROR, "发票作废失败，该税号下无设备或设备未启用，请启用后重试！");
            }
            if (CodeConstant.A9.equals(equipmentEntity.getEquipmentMode())) {
                response = dealInvoiceCancelA9(serialNo);
            } else {
                response = invoiceCancelSST(equipmentEntity, invoiceEntity);
            }
            if (CodeConstant.T0001.equals(response.getCode())) {
                break;
            }
        }
        return response;
    }

    /**
     * 发票作废（税神通）
     *
     * @param
     * @return
     */
    public Response invoiceCancelSST(EquipmentEntity entity, SellerInvoiceEntity sellerInvoiceEntity) {
        String json = IntJsonUtil.cancelInvoice(entity.getEquipmentMode(), entity.getAppid(), sellerInvoiceEntity);
        SellerInvoiceDTO sellerInvoiceDTO = new SellerInvoiceDTO();
        sellerInvoiceDTO.setBw(json);
        Response response = apiClientService.callSST(sellerInvoiceDTO);
        String result = (String) response.getData();
        JSONObject jsonObject = (JSONObject) JSON.parse(result);
        String code = jsonObject.getString("code");
        String msg = jsonObject.getString("msg");
        if (CodeConstant.THIRD_PARTY_SUCCESS.equals(code)) {
            String oldInvoiceCode = sellerInvoiceEntity.getOldInvoiceCode();
            String oldInvoiceNo = sellerInvoiceEntity.getOldInvoiceNo();
            String invoiceCode = sellerInvoiceEntity.getInvoiceCode();
            String invoiceNo = sellerInvoiceEntity.getInvoiceNo();
            if (!StringUtil.isEmpty(oldInvoiceCode) && !StringUtil.isEmpty(oldInvoiceNo)) {
                QueryWrapper<SellerInvoiceEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("invoice_code", oldInvoiceCode);
                queryWrapper.eq("invoice_no", oldInvoiceNo);
                SellerInvoiceEntity redSellerInvoiceEntity = new SellerInvoiceEntity();
                redSellerInvoiceEntity.setInvoiceState(CodeConstant.COMM_CODE_0);
                baseMapper.update(redSellerInvoiceEntity, queryWrapper);
                QueryWrapper<SellerInvoiceEntity> invoiceQuery = new QueryWrapper<>();
                invoiceQuery.eq("invoice_code", invoiceCode);
                invoiceQuery.eq("invoice_no", invoiceNo);
                SellerInvoiceEntity redInfoSellerInvoiceEntity = new SellerInvoiceEntity();
                redInfoSellerInvoiceEntity.setInvoiceState(CodeConstant.COMM_CODE_1);
                baseMapper.update(redInfoSellerInvoiceEntity, invoiceQuery);
            } else {
                sellerInvoiceEntity.setInvoiceState("1");
                this.updateById(sellerInvoiceEntity);
                //作废成功，更新docId表中的状态
                updateCancelSuccessStatus(sellerInvoiceEntity.getDocId(), sellerInvoiceEntity.getInvoiceType());
            }
        } else {
            //作废失败，更新docId表中的状态
            updateCancelFailStatus(sellerInvoiceEntity.getDocId());
            return Response.error(CodeConstant.T0001, msg);
        }
        return Response.success();
    }

    /**
     * 发票作废(A9)
     *
     * @param serialNo
     * @return
     */
    public Response dealInvoiceCancelA9(String serialNo) {
        QueryWrapper<SellerInvoiceEntity> invoiceQuery = new QueryWrapper<>();
        invoiceQuery.eq("serial_no", serialNo);
        SellerInvoiceEntity sellerInvoiceEntity = baseMapper.selectOne(invoiceQuery);
        String url = zzsfpUrl + "busiInterface";
        String interfaceCode = "EI.YKFPZF.U.EC.INTRA";
        String nsrsbh = sellerInvoiceEntity.getSellerTaxNo();
        if (sellerInvoiceEntity != null) {
            String fplx = InvoiceHelper.transFplxdm(sellerInvoiceEntity.getInvoiceType());
            SellerInvoiceEntity sie = new SellerInvoiceEntity();
            sie.setInvoiceType(fplx);//发票类型
            sie.setInvoiceCode(sellerInvoiceEntity.getInvoiceCode());//发票号码
            sie.setInvoiceNo(sellerInvoiceEntity.getInvoiceNo());//发票代码
            //判断docId是否为空，不为空则为明源发票，需回传信息给明源
            String docId = sellerInvoiceEntity.getDocId();
            String ykInvoiceData = FreemarkUtil.getTemplateObj("ykCancelInvoice.ftl", sie);
            String xmlData = InvoiceHelper.getXmlData(ykInvoiceData, interfaceCode, nsrsbh, null);
            InterfaceDTO interfaceDTO = new InterfaceDTO();
            interfaceDTO.setXmlData(xmlData);
            interfaceDTO.setUrl(url);
            Response response = apiClientService.callSales(interfaceDTO);
            if (CodeConstant.T0000.equals(response.getCode())) {
                sellerInvoiceEntity.setInvoiceState("1");
                this.updateById(sellerInvoiceEntity);
                //作废成功，更新docId表中的状态
                updateCancelSuccessStatus(docId, sellerInvoiceEntity.getInvoiceType());
            } else {
                //作废失败，更新docId表中的状态
                updateCancelFailStatus(docId);
                return Response.error(CodeConstant.T0001, response.getMsg());
            }
        }
        return Response.success();
    }

    /**
     * 普票红冲
     *
     * @param serialNo
     * @return
     */
    public Response makeRedCommonInvoice(String serialNo) {
        QueryWrapper<SellerInvoiceEntity> invoiceQuery = new QueryWrapper<>();
        invoiceQuery.eq("serial_no", serialNo);
        SellerInvoiceEntity sellerInvoiceEntity = this.getOne(invoiceQuery);
        String invoiceType = sellerInvoiceEntity.getInvoiceType();
        String makeInvoiceType = sellerInvoiceEntity.getMakeInvoiceType();
        String invoiceState = sellerInvoiceEntity.getInvoiceState();
        String invoiceCode = sellerInvoiceEntity.getInvoiceCode();
        String invoiceNo = sellerInvoiceEntity.getInvoiceNo();
        String invoiceDate = sellerInvoiceEntity.getInvoiceDate();
        String month = DateUtil.currentMonth();
        String[] invoiceDateArr = invoiceDate.split("-");
        String uuid = UUIDUitl.UUID32(false);
        if (invoiceType.equals("007") || invoiceType.equals("026")) {
            if (invoiceType.equals("007")) {
                if (month.equals(invoiceDateArr[1])) {
                    return Response.error("T0001", "当月发票不能红冲！");
                }
            }
            if (makeInvoiceType.equals("0")) {
                if (invoiceState.equals("0")) {
                    QueryWrapper<SellerInvoiceDetailEntity> invoiceDQuery = new QueryWrapper<>();
                    invoiceDQuery.eq("serial_no", serialNo);
                    invoiceDQuery.orderByAsc("detail_no");
                    List<SellerInvoiceDetailEntity> sellerInvoiceDetailEntityList = invoiceDetailService.list(invoiceDQuery);
                    List newList = new ArrayList();
                    int sellerInvoiceDetailEntityListSize = sellerInvoiceDetailEntityList.size();
                    for (int i = 0; i < sellerInvoiceDetailEntityListSize; i++) {
                        SellerInvoiceDetailEntity sellerInvoiceDetailEntity = sellerInvoiceDetailEntityList.get(i);
                        sellerInvoiceDetailEntity.setUuid(UUIDUitl.UUID32(false));
                        if (isSpecialChar(sellerInvoiceDetailEntity.getGoodsName())) {
                            String[] strArr = sellerInvoiceDetailEntity.getGoodsName().split("\\*");
                            sellerInvoiceDetailEntity.setGoodsName(strArr[1]);
                        }
                        sellerInvoiceDetailEntity.setSerialNo(uuid);
                        String invoiceRowNature = sellerInvoiceDetailEntity.getInvoiceRowNature();
                        String goodNumber = sellerInvoiceDetailEntity.getGoodsNumber();
                        String goodSum = sellerInvoiceDetailEntity.getGoodsSum();
                        String goodTax = sellerInvoiceDetailEntity.getGoodTax();
                        if (invoiceRowNature.equals("2")) {
                            SellerInvoiceDetailEntity sellerInvoiceDetailEntityNext = sellerInvoiceDetailEntityList.get(i + 1);
                            String goodNumberNext = sellerInvoiceDetailEntityNext.getGoodsNumber();
                            String goodSumNext = sellerInvoiceDetailEntityNext.getGoodsSum();
                            String goodTaxNext = sellerInvoiceDetailEntityNext.getGoodTax();

                            double goodSumDouble = Arith.add(Double.valueOf(goodSum), Double.valueOf(goodSumNext));
                            double goodTaxDouble = Arith.add(Double.valueOf(goodTax), Double.valueOf(goodTaxNext));
                            if (StringUtils.isNotBlank(goodNumber)) {
                                double goodNumberDouble = Arith.add(Double.valueOf(goodNumber), Double.valueOf(goodNumberNext));
                                if (goodNumberDouble > 0) {
                                    double unitPriceDouble = Arith.div(goodSumDouble, goodNumberDouble, 8);
                                    sellerInvoiceDetailEntity.setUnitPrice("-" + String.valueOf(unitPriceDouble));
                                }
                                sellerInvoiceDetailEntity.setGoodsNumber("-" + String.valueOf(goodNumberDouble));
                            }
                            sellerInvoiceDetailEntity.setGoodsSum("-" + String.valueOf(goodSumDouble));
                            sellerInvoiceDetailEntity.setGoodTax("-" + String.valueOf(goodTaxDouble));
                            if (goodSumDouble != 0) {
                                newList.add(sellerInvoiceDetailEntity);
                            }
                        } else if (invoiceRowNature.equals("0")) {
                            if (StringUtils.isNotBlank(goodNumber)) {
                                sellerInvoiceDetailEntity.setGoodsNumber("-" + goodNumber);
                            }
                            sellerInvoiceDetailEntity.setGoodsSum("-" + sellerInvoiceDetailEntity.getGoodsSum());
                            sellerInvoiceDetailEntity.setGoodTax("-" + sellerInvoiceDetailEntity.getGoodTax());
                            sellerInvoiceDetailEntity.setGoodsSumTax("-" + sellerInvoiceDetailEntity.getGoodsSumTax());
                            newList.add(sellerInvoiceDetailEntity);
                        }
                    }
                    sellerInvoiceEntity.setUuid(UUIDUitl.UUID32(false));
                    sellerInvoiceEntity.setSerialNo(uuid);
                    sellerInvoiceEntity.setInvoiceNo("");
                    sellerInvoiceEntity.setInvoiceCode("");
                    sellerInvoiceEntity.setInvoiceDate("");
                    sellerInvoiceEntity.setInvoiceState("0");
                    sellerInvoiceEntity.setMakeInvoiceState("0");
                    sellerInvoiceEntity.setCheckCode("");
                    sellerInvoiceEntity.setPanNo("");
                    sellerInvoiceEntity.setTotalSum("-" + sellerInvoiceEntity.getTotalSum());
                    sellerInvoiceEntity.setTotalTax("-" + sellerInvoiceEntity.getTotalTax());
                    sellerInvoiceEntity.setTotalSumTax("-" + sellerInvoiceEntity.getTotalSumTax());
                    sellerInvoiceEntity.setDiscountSum("0");
                    sellerInvoiceEntity.setDiscountSumTax("0");
                    sellerInvoiceEntity.setDiscountTax("0");
                    sellerInvoiceEntity.setPrintState("0");
                    sellerInvoiceEntity.setInvoiceMonth("");
                    sellerInvoiceEntity.setInvoiceDay("");
                    sellerInvoiceEntity.setInvoiceUrl("");
                    sellerInvoiceEntity.setCipherText("");
                    sellerInvoiceEntity.setMakeInvoiceType("1");
                    sellerInvoiceEntity.setOldInvoiceNo(invoiceNo);
                    sellerInvoiceEntity.setOldInvoiceCode(invoiceCode);
                    sellerInvoiceEntity.setCreateTime(new Date());
                    sellerInvoiceEntity.setUpdateTime(new Date());
                    sellerInvoiceEntity.setRemark("对应正数发票代码：" + invoiceCode + "号码：" + invoiceNo);
                    this.save(sellerInvoiceEntity);
                    invoiceDetailService.saveBatch(newList);
                    QueryWrapper<SellerInvoiceEntity> invoiceQuery1 = new QueryWrapper<>();
                    invoiceQuery1.eq("serial_no", serialNo);
                    SellerInvoiceEntity sie = this.getOne(invoiceQuery1);
                    sie.setInvoiceState("2");
                    this.updateById(sie);
                    //根据发票代码号码更新发票池的发票状态
                    sellerInvoiceEntity.setInvoiceCode(invoiceCode);
                    sellerInvoiceEntity.setInvoiceNo(invoiceNo);
                    updateCancelOrderSate(sellerInvoiceEntity, "3");
                } else {
                    return Response.error("T0001", "只能选择正常发票！");
                }
            } else {
                return Response.error("T0001", "只能选择正数发票！");
            }
        } else {
            return Response.error("T0001", "只能选择普通发票！");
        }
        return Response.success();
    }

    /**
     * 机动车普票红冲
     *
     * @param serialNo 发票流水号
     * @return 结果
     */
    public Response carMakeRedCommonInvoice(String serialNo) {
        QueryWrapper<SellerInvoiceEntity> invoiceQuery = new QueryWrapper<>();
        invoiceQuery.eq("serial_no", serialNo);
        //发票信息
        SellerInvoiceEntity sellerInvoiceEntity = this.getOne(invoiceQuery);
        String invoiceType = sellerInvoiceEntity.getInvoiceType();
        String makeInvoiceType = sellerInvoiceEntity.getMakeInvoiceType();
        String invoiceState = sellerInvoiceEntity.getInvoiceState();
        String invoiceCode = sellerInvoiceEntity.getInvoiceCode();
        String invoiceNo = sellerInvoiceEntity.getInvoiceNo();
        String uuid = UUIDUitl.UUID32(false);
        if (!invoiceType.equals("005")) {
            return Response.error("T0001", "只能选择机动车普通发票！");
        }
        if (!makeInvoiceType.equals("0")) {
            return Response.error("T0001", "只能选择正数发票！");
        }
        if (!invoiceState.equals("0")) {
            return Response.error("T0001", "只能选择正常发票！");
        }
        QueryWrapper<SellerInvoiceDetailEntity> invoiceDQuery = new QueryWrapper<>();
        invoiceDQuery.eq("serial_no", serialNo);
        invoiceDQuery.orderByAsc("detail_no");
        //发票明细
        List<SellerInvoiceDetailEntity> sellerInvoiceDetailEntityList = invoiceDetailService.list(invoiceDQuery);
        SellerInvoiceDetailEntity sellerInvoiceDetailEntity = sellerInvoiceDetailEntityList.get(0);
        //新增红票明细信息
        sellerInvoiceDetailEntity.setUuid(UUIDUitl.UUID32(false));
        sellerInvoiceDetailEntity.setCarCategoryName(sellerInvoiceDetailEntity.getGoodsName());
        sellerInvoiceDetailEntity.setSerialNo(uuid);
        if (StringUtils.isNotBlank(sellerInvoiceDetailEntity.getGoodsNumber())) {
            sellerInvoiceDetailEntity.setGoodsNumber("-" + sellerInvoiceDetailEntity.getGoodsNumber());
        }
        sellerInvoiceDetailEntity.setGoodsSum("-" + sellerInvoiceDetailEntity.getGoodsSum());
        sellerInvoiceDetailEntity.setGoodTax("-" + sellerInvoiceDetailEntity.getGoodTax());
        sellerInvoiceDetailEntity.setGoodsSumTax("-" + sellerInvoiceDetailEntity.getGoodsSumTax());

        //新增红票信息
        sellerInvoiceEntity.setUuid(UUIDUitl.UUID32(false));
        sellerInvoiceEntity.setSerialNo(uuid);
        sellerInvoiceEntity.setInvoiceNo("");
        sellerInvoiceEntity.setInvoiceCode("");
        sellerInvoiceEntity.setInvoiceDate("");
        sellerInvoiceEntity.setInvoiceState("0");
        sellerInvoiceEntity.setMakeInvoiceState("0");
        sellerInvoiceEntity.setCheckCode("");
        sellerInvoiceEntity.setPanNo("");
        sellerInvoiceEntity.setTotalSum("-" + sellerInvoiceEntity.getTotalSum());
        sellerInvoiceEntity.setTotalTax("-" + sellerInvoiceEntity.getTotalTax());
        sellerInvoiceEntity.setTotalSumTax("-" + sellerInvoiceEntity.getTotalSumTax());
        sellerInvoiceEntity.setDiscountSum("0");
        sellerInvoiceEntity.setDiscountSumTax("0");
        sellerInvoiceEntity.setDiscountTax("0");
        sellerInvoiceEntity.setPrintState("0");
        sellerInvoiceEntity.setInvoiceMonth("");
        sellerInvoiceEntity.setInvoiceDay("");
        sellerInvoiceEntity.setInvoiceUrl("");
        sellerInvoiceEntity.setCipherText("");
        sellerInvoiceEntity.setMakeInvoiceType("1");
        sellerInvoiceEntity.setOldInvoiceNo(invoiceNo);
        sellerInvoiceEntity.setOldInvoiceCode(invoiceCode);
        sellerInvoiceEntity.setCreateTime(new Date());
        sellerInvoiceEntity.setUpdateTime(new Date());
        sellerInvoiceEntity.setRemark("对应正数发票代码：" + invoiceCode + "号码：" + invoiceNo);
        this.save(sellerInvoiceEntity);
        invoiceDetailService.save(sellerInvoiceDetailEntity);
        QueryWrapper<SellerInvoiceEntity> invoiceQuery1 = new QueryWrapper<>();
        invoiceQuery1.eq("serial_no", serialNo);
        SellerInvoiceEntity sie = this.getOne(invoiceQuery1);
        sie.setInvoiceState("2");
        this.updateById(sie);
        return Response.success();
    }

    public void updateCancelOrderSate(SellerInvoiceEntity sellerInvoiceEntity, String invoiceStatus) {
        String orderNo = sellerInvoiceEntity.getOrderNo();
        List<SellerInvoiceEntity> invoiceEntityList = this.list(new QueryWrapper<SellerInvoiceEntity>().eq("order_no", orderNo).eq("make_invoice_type", "0").eq("invoice_state", "0"));

        if (invoiceEntityList != null && invoiceEntityList.size() != 0) {
            List<DocumentInfoEntity> soeList = documentInfoService.list(new QueryWrapper<DocumentInfoEntity>().eq("doc_id", orderNo));
            for (DocumentInfoEntity soe : soeList) {
                //soe.setOrderState("0");
                documentInfoService.updateById(soe);
            }
        }
    }

    /**
     * 红字信息申请
     *
     * @param redInvoiceInfoFirstDTO
     * @return
     */
    public Response reqRedInvoiceInfoFirst(RedInvoiceInfoFirstDTO redInvoiceInfoFirstDTO) {
        String invoiceCode = redInvoiceInfoFirstDTO.getInvoiceCode();
        String invoiceNo = redInvoiceInfoFirstDTO.getInvoiceNo();
        SellerInvoiceEntity sellerInvoiceEntity = this.getOne(new QueryWrapper<SellerInvoiceEntity>().eq("invoice_code", invoiceCode).eq("invoice_no", invoiceNo));
        if (sellerInvoiceEntity == null) {
            return Response.error("T0001", "没有此张发票信息！");
        } else {
            String invoiceState = sellerInvoiceEntity.getInvoiceState();
            String serialNo = sellerInvoiceEntity.getSerialNo();
            String invoiceDate = sellerInvoiceEntity.getInvoiceDate();

            List<SellerInvoiceDetailEntity> newSellerInvoiceDetailEntityList = new ArrayList<SellerInvoiceDetailEntity>();
            List<SellerInvoiceDetailEntity> sellerInvoiceDetailEntityList = invoiceDetailService.list(new QueryWrapper<SellerInvoiceDetailEntity>().eq("serial_no", serialNo).orderByAsc("detail_no"));
            if (sellerInvoiceDetailEntityList == null || sellerInvoiceDetailEntityList.size() == 0) {
                invoiceState = "5";
            }

            if (invoiceState.equals("5") || invoiceState.equals("2")) {
                return Response.error("T0001", "此张发票已经红冲！");
            } else if (invoiceState.equals("1")) {
                return Response.error("T0001", "此张发票已作废，不能红冲！");
            }

            String month = DateUtil.currentMonth();
            String[] invoiceDateArr = invoiceDate.split("-");
            if (!month.equals(invoiceDateArr[1])) {
                sellerInvoiceEntity.setCapitalTotalSumTax("负" + BeanSelfUtils.change(DoubleUtils.stringFormatdouble(sellerInvoiceEntity.getTotalSumTax())));
                sellerInvoiceEntity.setTotalSum("-" + sellerInvoiceEntity.getTotalSum());
                sellerInvoiceEntity.setTotalTax("-" + sellerInvoiceEntity.getTotalTax());
                sellerInvoiceEntity.setTotalSumTax("-" + sellerInvoiceEntity.getTotalSumTax());
                sellerInvoiceEntity.setOldInvoiceNo(sellerInvoiceEntity.getInvoiceNo());
                sellerInvoiceEntity.setOldInvoiceCode(sellerInvoiceEntity.getInvoiceCode());
                sellerInvoiceEntity.setSellerApplyReason(redInvoiceInfoFirstDTO.getSellerApplyReason());
                int sellerInvoiceDetailEntityListSize = sellerInvoiceDetailEntityList.size();
                if (sellerInvoiceDetailEntityListSize > 8) {
                    SellerInvoiceDetailEntity sellerInvoiceDetailEntity = sellerInvoiceDetailEntityList.get(0);
                    sellerInvoiceDetailEntity.setGoodsName("(详见销货清单)");
                    String totalSum = sellerInvoiceEntity.getTotalSum();
                    String totalTax = sellerInvoiceEntity.getTotalTax();
                    double goodSumTax = Arith.add(Double.valueOf(totalSum), Double.valueOf(totalTax));
                    sellerInvoiceDetailEntity.setGoodsSum(totalSum);
                    sellerInvoiceDetailEntity.setGoodTax(totalTax);
                    sellerInvoiceDetailEntity.setGoodsSumTax(String.valueOf(goodSumTax));
                    sellerInvoiceDetailEntity.setUnitPrice("");
                    sellerInvoiceDetailEntity.setUnit("");
                    sellerInvoiceDetailEntity.setSellerTaxNo(sellerInvoiceEntity.getSellerTaxNo());
                    newSellerInvoiceDetailEntityList.add(sellerInvoiceDetailEntity);
                    sellerInvoiceEntity.setInvoiceDetail(newSellerInvoiceDetailEntityList);
                } else {
                    for (int i = 0; i < sellerInvoiceDetailEntityListSize; i++) {
                        SellerInvoiceDetailEntity sellerInvoiceDetailEntity = sellerInvoiceDetailEntityList.get(i);
                        String invoiceRowNature = sellerInvoiceDetailEntity.getInvoiceRowNature();
                        if (isSpecialChar(sellerInvoiceDetailEntity.getGoodsName())) {
                            String[] strArr = sellerInvoiceDetailEntity.getGoodsName().split("\\*");
                            sellerInvoiceDetailEntity.setGoodsName(strArr[1]);
                        }
                        sellerInvoiceDetailEntity.setSellerTaxNo(sellerInvoiceEntity.getSellerTaxNo());
                        String goodNumber = sellerInvoiceDetailEntity.getGoodsNumber();
                        String goodSum = sellerInvoiceDetailEntity.getGoodsSum();
                        String goodTax = sellerInvoiceDetailEntity.getGoodTax();
                        if (invoiceRowNature.equals("2")) {
                            SellerInvoiceDetailEntity sellerInvoiceDetailEntityNext = sellerInvoiceDetailEntityList.get(i + 1);
                            String goodNumberNext = sellerInvoiceDetailEntityNext.getGoodsNumber();
                            String goodSumNext = sellerInvoiceDetailEntityNext.getGoodsSum();
                            String goodTaxNext = sellerInvoiceDetailEntityNext.getGoodTax();
                            double goodSumDouble = Arith.add(Double.valueOf(goodSum), Double.valueOf(goodSumNext));
                            double goodTaxDouble = Arith.add(Double.valueOf(goodTax), Double.valueOf(goodTaxNext));
                            if (StringUtils.isNotBlank(goodNumber)) {
                                double goodNumberDouble = Arith.add(Double.valueOf(goodNumber), StringUtils.isEmpty(goodNumberNext) ? 0 : Double.valueOf(goodNumberNext));
                                if (goodNumberDouble > 0) {
                                    double unitPriceDouble = Arith.div(goodSumDouble, goodNumberDouble, 8);
                                    sellerInvoiceDetailEntity.setUnitPrice("-" + String.valueOf(unitPriceDouble));
                                }
                                sellerInvoiceDetailEntity.setGoodsNumber("-" + String.valueOf(goodNumberDouble));
                            }
                            sellerInvoiceDetailEntity.setGoodsSum("-" + String.valueOf(goodSumDouble));
                            sellerInvoiceDetailEntity.setGoodTax("-" + String.valueOf(goodTaxDouble));
                            if (goodSumDouble != 0) {
                                newSellerInvoiceDetailEntityList.add(sellerInvoiceDetailEntity);
                            }
                        } else if (invoiceRowNature.equals("0")) {
                            if (StringUtils.isNotBlank(goodNumber)) {
                                sellerInvoiceDetailEntity.setGoodsNumber("-" + goodNumber);
                            }
                            sellerInvoiceDetailEntity.setGoodsSum("-" + sellerInvoiceDetailEntity.getGoodsSum());
                            sellerInvoiceDetailEntity.setGoodTax("-" + sellerInvoiceDetailEntity.getGoodTax());
                            sellerInvoiceDetailEntity.setGoodsSumTax("-" + sellerInvoiceDetailEntity.getGoodsSumTax());
                            newSellerInvoiceDetailEntityList.add(sellerInvoiceDetailEntity);
                        }
                    }
                }
                sellerInvoiceEntity.setInvoiceDetail(newSellerInvoiceDetailEntityList);
            } else {
                return Response.error("T0001", "当月发票，不能红冲！");
            }
        }
        return Response.success(sellerInvoiceEntity);
    }

    /**
     * 下一步开始红字申请
     *
     * @return
     */
    public Response reqRedInvoiceInfoTwo(SellerInvoiceRVO sellerInvoiceRVo) {
        Response response = new Response();
        SellerInvoiceEntity sellerInvoiceEntity = DozerBeanUtil.map(sellerInvoiceRVo, SellerInvoiceEntity.class);
        sellerInvoiceEntity.setFplx(InvoiceHelper.transFplxdm(sellerInvoiceEntity.getInvoiceType()));
        SimpleDateFormat shortSdfd = new SimpleDateFormat("yyyyMMddHHmmss");
        String dateStr = shortSdfd.format(new Date());
        sellerInvoiceEntity.setREQBILLNO(sellerInvoiceEntity.getPanNo() + dateStr);
        //生成红字发票表信息
        String uuid = UUIDUitl.UUID32(false);
        SellerRedInvoiceEntity sellerRedInvoiceEntity = new SellerRedInvoiceEntity();
        sellerRedInvoiceEntity.setUuid(uuid);
        sellerRedInvoiceEntity.setPurchaserName(sellerInvoiceEntity.getPurchaserName());
        sellerRedInvoiceEntity.setPurchaserTaxNo(sellerInvoiceEntity.getPurchaserTaxNo());
        sellerRedInvoiceEntity.setSellerName(sellerInvoiceEntity.getSellerName());
        sellerRedInvoiceEntity.setSellerTaxNo(sellerInvoiceEntity.getSellerTaxNo());
        sellerRedInvoiceEntity.setTotalSumTax(sellerInvoiceEntity.getTotalSumTax());
        sellerRedInvoiceEntity.setTotalSum(sellerInvoiceEntity.getTotalSum());
        sellerRedInvoiceEntity.setTotalTax(sellerInvoiceEntity.getTotalTax());
        sellerRedInvoiceEntity.setReqTaxNo(sellerInvoiceEntity.getSellerTaxNo());
        sellerRedInvoiceEntity.setReqType("0");
        sellerRedInvoiceEntity.setInvoiceCode(sellerInvoiceEntity.getInvoiceCode());
        sellerRedInvoiceEntity.setInvoiceNo(sellerInvoiceEntity.getInvoiceNo());
        sellerRedInvoiceEntity.setReqNo(sellerInvoiceEntity.getREQBILLNO());
        sellerRedInvoiceEntity.setInputDate(sellerInvoiceEntity.getInvoiceDate());
        sellerRedInvoiceEntity.setSellerApplyReason(sellerInvoiceRVo.getSellerApplyReason());
        //获取yyyymm
        String currentDate = new SimpleDateFormat(CommonConstant.DATE_FORMAT_THREE).format(new Date());
        sellerInvoiceEntity.setInvoiceDate(currentDate);
        //根据税盘不同处理
        EquipmentEntity equipmentEntity = equipmentService.getOne(new QueryWrapper<EquipmentEntity>().eq("seller_tax_no", sellerInvoiceEntity.getSellerTaxNo()));
        if (equipmentEntity == null || CodeConstant.COMM_CODE_0.equals(equipmentEntity.getDisable())) {
            return Response.error(CodeConstant.ERROR, "SEL_038");
        }
        if (CodeConstant.COMM_CODE_4.equals(equipmentEntity.getEquipmentMode())) {
            response = reqRedInvoiceInfoTwoA9(sellerInvoiceEntity, sellerRedInvoiceEntity);
        } else {
            response = reqRedInvoiceInfoTwoSST(sellerInvoiceEntity, equipmentEntity, sellerRedInvoiceEntity);
        }
        return response;
    }

    /**
     * 下一步开始红字申请(SST)
     *
     * @param sellerInvoiceEntity
     * @param equipmentEntity
     * @return
     */
    public Response reqRedInvoiceInfoTwoSST(SellerInvoiceEntity sellerInvoiceEntity, EquipmentEntity equipmentEntity, SellerRedInvoiceEntity sellerRedInvoiceEntity) {
        Response res = new Response();
        String json = IntJsonUtil.redInvoiceInfoUpload(equipmentEntity.getEquipmentMode(), equipmentEntity.getAppid(), equipmentEntity.getPanNo(), sellerInvoiceEntity, sellerInvoiceEntity.getInvoiceDetail());
        SellerInvoiceDTO sellerInvoiceDTO = new SellerInvoiceDTO();
        sellerInvoiceDTO.setBw(json);
        Response response = apiClientService.callSST(sellerInvoiceDTO);
        String result = (String) response.getData();
        JSONObject jsonObject = (JSONObject) JSON.parse(result);
        String code = jsonObject.getString("code");
        String msg = jsonObject.getString("msg");
        res.setMsg(msg);
        try {
            if (CodeConstant.THIRD_PARTY_SUCCESS.equals(code)) {
                Map resMap = (Map) jsonObject.get("data");
                String xxbbh = MapUtils.getString(resMap, "xxbbh", "");
                if (xxbbh.equals("")) {
                    sellerRedInvoiceEntity.setTicketState("1");
                } else {
                    sellerRedInvoiceEntity.setTicketState("0");
                }
                sellerRedInvoiceEntity.setReqDate(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
                sellerRedInvoiceEntity.setInputDate(new SimpleDateFormat("yyyy-MM-dd ").format(new Date()));
                sellerRedInvoiceEntity.setRedInfoNo(xxbbh);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<SellerInvoiceDetailEntity> sellerInvoiceDetailEntityList = sellerInvoiceEntity.getInvoiceDetail();
        List idList = new ArrayList();
        List<SellerRedInvoiceDetailEntity> sellerRedInvoiceDetailEntityList = new ArrayList<SellerRedInvoiceDetailEntity>();
        for (int i = 0; i < sellerInvoiceDetailEntityList.size(); i++) {
            SellerInvoiceDetailEntity sellerInvoiceDetailEntity = sellerInvoiceDetailEntityList.get(i);
            SellerRedInvoiceDetailEntity sellerRedInvoiceDetailEntity = new SellerRedInvoiceDetailEntity();
            String id = sellerInvoiceDetailEntity.getUuid();
            idList.add(id);
            sellerRedInvoiceDetailEntity.setUuid(id);
            sellerRedInvoiceDetailEntity.setRedInfoId(sellerRedInvoiceEntity.getUuid());
            sellerRedInvoiceDetailEntity.setGoodsName(sellerInvoiceDetailEntity.getGoodsName());
            sellerRedInvoiceDetailEntity.setUnit(sellerInvoiceDetailEntity.getUnit());
            sellerRedInvoiceDetailEntity.setUnitPrice(sellerInvoiceDetailEntity.getUnitPrice());
            sellerRedInvoiceDetailEntity.setGoodNumber(sellerInvoiceDetailEntity.getGoodsNumber());
            sellerRedInvoiceDetailEntity.setGoodsSum(sellerInvoiceDetailEntity.getGoodsSum());
            sellerRedInvoiceDetailEntity.setTaxRate(sellerInvoiceDetailEntity.getTaxRate());
            sellerRedInvoiceDetailEntity.setGoodTax(sellerInvoiceDetailEntity.getGoodTax());
            sellerRedInvoiceDetailEntity.setTaxRateMark(sellerInvoiceDetailEntity.getTaxRateMark());
            sellerRedInvoiceDetailEntity.setPreferentialMark(sellerInvoiceDetailEntity.getPreferentialMark());
            sellerRedInvoiceDetailEntity.setPreferentialName(sellerInvoiceDetailEntity.getPreferentialName());
            sellerRedInvoiceDetailEntity.setTaxCode(sellerInvoiceDetailEntity.getTaxCode());
            sellerRedInvoiceDetailEntity.setDetailNo(sellerInvoiceDetailEntity.getDetailNo());
            sellerRedInvoiceDetailEntity.setSellerTaxNo(sellerInvoiceDetailEntity.getSellerTaxNo());
            sellerRedInvoiceDetailEntityList.add(sellerRedInvoiceDetailEntity);
        }
        redTicketService.save(sellerRedInvoiceEntity);
        sellerRedInvoiceDetailService.saveBatch(sellerRedInvoiceDetailEntityList);
        //查找所有与发票明细相同的红字明细
        List<SellerRedInvoiceDetailEntity> srdeList = sellerRedInvoiceDetailService.list(new QueryWrapper<SellerRedInvoiceDetailEntity>().in("uuid", idList));
        for (SellerRedInvoiceDetailEntity srde : srdeList) {
            srde.setRedMark("1");
            sellerRedInvoiceDetailService.updateById(srde);
        }
        SellerInvoiceEntity sie = this.getOne(new QueryWrapper<SellerInvoiceEntity>().eq("invoice_code", sellerInvoiceEntity.getInvoiceCode()).eq("invoice_no", sellerInvoiceEntity.getInvoiceNo()));
        sie.setInvoiceState("2");
        this.updateById(sie);
        //返回红字发票id,一步生成至待开
        ArrayList<String> ids = new ArrayList<>();
        ids.add(sellerRedInvoiceEntity.getUuid());
        return Response.success(ids);
    }

    /**
     * 红字信息表下载SST
     *
     * @param vo
     * @return
     */
    public Response downloadRedInvoiceInfo(DownloadRedInvoiceVO vo) {
        Response res = new Response();
        //根据税盘不同处理
        EquipmentEntity equipmentEntity = equipmentService.getOne(new QueryWrapper<EquipmentEntity>().eq("seller_tax_no", vo.getSellerTaxNo()));
        if (equipmentEntity == null || CodeConstant.COMM_CODE_0.equals(equipmentEntity.getDisable())) {
            return Response.error("SEL_038");
        }
        //拼接报文
        String json = IntJsonUtil.downLoadRedInfo(equipmentEntity.getAppid(), vo.getApplicationNo(), vo.getStartDate(), vo.getEndDate(), vo.getSellerTaxNo());
        //调用税神通
        SellerInvoiceDTO sellerInvoiceDTO = new SellerInvoiceDTO();
        sellerInvoiceDTO.setBw(json);
        Response response = apiClientService.callSST(sellerInvoiceDTO);
        String result = (String) response.getData();
        JSONObject jsonObject = (JSONObject) JSON.parse(result);
        String code = jsonObject.getString("code");
        String msg = jsonObject.getString("msg");
        res.setMsg(msg);


        try {
            if (CodeConstant.THIRD_PARTY_SUCCESS.equals(code)) {
                List resList = (List) jsonObject.get("data");
                SyncInvoiceDTO syncInvoiceDTO = new SyncInvoiceDTO();
                syncInvoiceDTO.setEquipmentMode(equipmentEntity.getEquipmentMode());
                syncInvoiceDTO.setSellerName(vo.getSellerName());
                syncInvoiceDTO.setSellerTaxNo(vo.getSellerTaxNo());
                //返回报文数据转换处理
                this.updateSellerRedInvoiceInfoSST(resList, syncInvoiceDTO);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Response.success();
    }


    /**
     * 税神通红字信息处理
     *
     * @param invoiceList    税神通返回数据
     * @param syncInvoiceDTO 销方信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateSellerRedInvoiceInfoSST(List<Map> invoiceList, SyncInvoiceDTO syncInvoiceDTO) {
//        String equipmentMode = syncInvoiceDTO.getEquipmentMode();
//        String sellerName = syncInvoiceDTO.getSellerName();
//        String taxNo = syncInvoiceDTO.getSellerTaxNo();

        //红字信息
        List<SellerRedInvoiceEntity> redInvoiceEntities = new ArrayList<>();

        //已有红字信息
        List<SellerRedInvoiceEntity> oldRedInvoiceEntities = new ArrayList<>();

        //需要删除的信息明细
        List<String> oldDetail = new ArrayList<>();

        //红字信息明细
        List<SellerRedInvoiceDetailEntity> redInvoiceDetailEntities = new ArrayList<>();

        for (Map invoiceMap : invoiceList) {
            //拼出信息表数据
            SellerRedInvoiceEntity newreRedInvoiceEntity = new SellerRedInvoiceEntity();
            String redInfoNo = MapUtils.getString(invoiceMap, "ResBillNo", "");
            String sellerTaxNo = MapUtils.getString(invoiceMap, "SellTaxCode", "");

            newreRedInvoiceEntity.setRedInfoNo(redInfoNo);
            newreRedInvoiceEntity.setSellerTaxNo(sellerTaxNo);
            newreRedInvoiceEntity.setReqNo(MapUtils.getString(invoiceMap, "ReqBillNo", ""));
            newreRedInvoiceEntity.setPurchaserTaxNo(MapUtils.getString(invoiceMap, "BuyTaxCode", ""));
            newreRedInvoiceEntity.setPurchaserName(MapUtils.getString(invoiceMap, "BuyerName", ""));
            newreRedInvoiceEntity.setSellerName(MapUtils.getString(invoiceMap, "SellerName", ""));
            newreRedInvoiceEntity.setTaxRate(MapUtils.getString(invoiceMap, "TaxRate", ""));
            String amount = MapUtils.getString(invoiceMap, "Amount", "");
            String tax = MapUtils.getString(invoiceMap, "Tax", "");
            newreRedInvoiceEntity.setTotalSum(amount);
            newreRedInvoiceEntity.setTotalTax(tax);
            newreRedInvoiceEntity.setTotalSumTax(add(amount, tax));
            newreRedInvoiceEntity.setReqTaxNo(MapUtils.getString(invoiceMap, "Sbbh", ""));
            newreRedInvoiceEntity.setInputDate(MapUtils.getString(invoiceMap, "Date", ""));
            newreRedInvoiceEntity.setReqDate(MapUtils.getString(invoiceMap, "Date", ""));
            String reqType = MapUtils.getString(invoiceMap, "ReqMemo", "");
            if (StringUtils.isNotEmpty(reqType)) {
                newreRedInvoiceEntity.setReqType(reqType.startsWith("X") ? "0" : "1");
            }
            newreRedInvoiceEntity.setInvoiceCode(MapUtils.getString(invoiceMap, "TypeCode", ""));
            newreRedInvoiceEntity.setInvoiceNo(MapUtils.getString(invoiceMap, "InvNo", ""));
            String ticketState = MapUtils.getString(invoiceMap, "StatusDM", "");
            newreRedInvoiceEntity.setTicketState(TransformationUtil.redTicketState(ticketState));
            QueryWrapper<SellerRedInvoiceEntity> invoiceQuery = new QueryWrapper<>();
            invoiceQuery.eq("red_info_no", redInfoNo);
            //invoiceQuery.eq("seller_tax_no", SellerTaxNo);
            SellerRedInvoiceEntity redInvoiceEntity = redTicketService.getOne(invoiceQuery);

            String redUUid;
            //红字信息表已经存在
            if (redInvoiceEntity != null) {
                redUUid = redInvoiceEntity.getUuid();
                newreRedInvoiceEntity.setUuid(redUUid);
                oldRedInvoiceEntities.add(newreRedInvoiceEntity);
                oldDetail.add(redUUid);
            } else {
                redUUid = UUIDUitl.UUID32(false);
                newreRedInvoiceEntity.setUuid(redUUid);
                redInvoiceEntities.add(newreRedInvoiceEntity);
            }


            //明细
            List detailList = (List) MapUtils.getObject(invoiceMap, "RedInvReqBillMx", new ArrayList());
            String slbz = MapUtils.getString(invoiceMap, "SLBZ", "");
            int detailListSize = detailList.size();
            for (int j = 0; j < detailListSize; j++) {
                Map detailMap = (Map) detailList.get(j);
                String redDetailUUid = UUIDUitl.UUID32(false);
                SellerRedInvoiceDetailEntity redInvoiceDetailEntity = new SellerRedInvoiceDetailEntity();
                redInvoiceDetailEntity.setRedInfoId(redUUid);
                redInvoiceDetailEntity.setUuid(redDetailUUid);
                redInvoiceDetailEntity.setGoodsName(MapUtils.getString(detailMap, "GoodsName", ""));
                redInvoiceDetailEntity.setGoodType(MapUtils.getString(detailMap, "GoodsGgxh", ""));
                redInvoiceDetailEntity.setUnit(MapUtils.getString(detailMap, "GoodsUnit", ""));
                redInvoiceDetailEntity.setUnitPrice(MapUtils.getString(detailMap, "GoodsPrice", ""));
                redInvoiceDetailEntity.setGoodNumber(MapUtils.getString(detailMap, "GoodsNUm", ""));
                String goodsSE = MapUtils.getString(detailMap, "GoodsSE", "");
                String goodsJE = MapUtils.getString(detailMap, "GoodsJE", "");
                redInvoiceDetailEntity.setGoodTax(goodsSE);
                if ("0".equals(slbz)) {
                    //不含税
                    redInvoiceDetailEntity.setGoodsSum(goodsJE);
                    redInvoiceDetailEntity.setGoodSumTax(add(goodsJE, goodsSE));
                } else {
                    //含税
                    redInvoiceDetailEntity.setGoodSumTax(goodsJE);
                    redInvoiceDetailEntity.setGoodsSum(subtract(goodsJE, goodsSE));
                }

                redInvoiceDetailEntity.setTaxRate(MapUtils.getString(detailMap, "GoodsTaxRate", ""));
                redInvoiceDetailEntity.setTaxRateMark(MapUtils.getString(detailMap, "LSLBS", ""));
                redInvoiceDetailEntity.setPreferentialMark(MapUtils.getString(detailMap, "SPYHZCBS", ""));
                redInvoiceDetailEntity.setPreferentialName(MapUtils.getString(detailMap, "YHZC", ""));
                redInvoiceDetailEntity.setTaxCode(MapUtils.getString(detailMap, "SPBM", ""));
                redInvoiceDetailEntity.setRedMark(StringUtils.equals("TZD0000", MapUtils.getString(detailMap, "StatusDm", "")) ? "1" : "0");
                redInvoiceDetailEntity.setSellerTaxNo(sellerTaxNo);

                redInvoiceDetailEntities.add(redInvoiceDetailEntity);

            }
        }

        //删除数据
        if (CollectionUtils.isNotEmpty(oldDetail)) {
            QueryWrapper<SellerRedInvoiceDetailEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("red_info_id", oldDetail);
            sellerRedInvoiceDetailService.remove(queryWrapper);
        }
        //修改信息表
        if (CollectionUtils.isNotEmpty(oldRedInvoiceEntities)) {
            redTicketService.updateBatchById(oldRedInvoiceEntities);
        }
        //新增信息表
        if (CollectionUtils.isNotEmpty(redInvoiceEntities)) {
            redTicketService.saveBatch(redInvoiceEntities);
        }
        //新增信息表明细
        if (CollectionUtils.isNotEmpty(redInvoiceDetailEntities)) {
            sellerRedInvoiceDetailService.saveBatch(redInvoiceDetailEntities);
        }
    }

    private String add(String num1, String num2) {
        BigDecimal bigDecimal1 = StringUtils.isEmpty(num1) ? new BigDecimal(0) : new BigDecimal(num1);
        BigDecimal bigDecimal2 = StringUtils.isEmpty(num2) ? new BigDecimal(0) : new BigDecimal(num2);
        return bigDecimal1.add(bigDecimal2).toString();
    }

    private String subtract(String num1, String num2) {
        BigDecimal bigDecimal1 = StringUtils.isEmpty(num1) ? new BigDecimal(0) : new BigDecimal(num1);
        BigDecimal bigDecimal2 = StringUtils.isEmpty(num2) ? new BigDecimal(0) : new BigDecimal(num2);
        return bigDecimal1.subtract(bigDecimal2).toString();
    }

    /**
     * 下一步开始红字申请(A9)
     *
     * @return
     */
    public Response reqRedInvoiceInfoTwoA9(SellerInvoiceEntity sellerInvoiceEntity, SellerRedInvoiceEntity sellerRedInvoiceEntity) {
        String redInvoiceData = FreemarkUtil.getTemplateObj("uploadRedInvoice.ftl", sellerInvoiceEntity);
        String url = zzsfpUrl + "busiInterface";
        String interfaceCode = "EI.HZFPSQBSC.U.EC.INTRA";
        String xmlData = InvoiceHelper.getXmlData(redInvoiceData, interfaceCode, sellerInvoiceEntity.getSellerTaxNo(), null);
        InterfaceDTO interfaceDTO = new InterfaceDTO();
        interfaceDTO.setXmlData(xmlData);
        interfaceDTO.setUrl(url);
        Response res = new Response<>();
        try {
            res = apiClientService.callSales(interfaceDTO);
            if (CodeConstant.T0000.equals(res.getCode())) {
                String reqcontent = res.getMsg();
                Map resMap = Xml2Map.Xml2Mapz(reqcontent);
                Map RESPONSE_COMMON_HZFPSQBSC = (Map) resMap.get("RESPONSE_COMMON_HZFPSQBSC");
                Map REDINVREQBILL = (Map) RESPONSE_COMMON_HZFPSQBSC.get("REDINVREQBILL");
                Map GOODSMX = (Map) REDINVREQBILL.get("GOODSMX");
                String xxbbh = GOODSMX.get("RESBILLNO").toString();
                if (xxbbh.equals("")) {
                    sellerRedInvoiceEntity.setTicketState("1");
                } else {
                    sellerRedInvoiceEntity.setTicketState("0");
                }
                sellerRedInvoiceEntity.setReqDate(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));
                sellerRedInvoiceEntity.setInputDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                sellerRedInvoiceEntity.setRedInfoNo(xxbbh);
            } else {
                return res;
            }
        } catch (Exception e) {
            log.info("SEL_029");
            return Response.error(CodeConstant.ERROR, "SEL_039");
        }

        List<SellerInvoiceDetailEntity> sellerInvoiceDetailEntityList = sellerInvoiceEntity.getInvoiceDetail();
        List idList = new ArrayList();
        List<SellerRedInvoiceDetailEntity> sellerRedInvoiceDetailEntityList = new ArrayList<SellerRedInvoiceDetailEntity>();
        //添加红字明细表信息
        for (int i = 0; i < sellerInvoiceDetailEntityList.size(); i++) {
            SellerInvoiceDetailEntity sellerInvoiceDetailEntity = sellerInvoiceDetailEntityList.get(i);
            SellerRedInvoiceDetailEntity sellerRedInvoiceDetailEntity = new SellerRedInvoiceDetailEntity();
            String id = sellerInvoiceDetailEntity.getUuid();
            idList.add(id);
            sellerRedInvoiceDetailEntity.setUuid(id);
            sellerRedInvoiceDetailEntity.setRedInfoId(sellerRedInvoiceEntity.getUuid());
            sellerRedInvoiceDetailEntity.setGoodsName(sellerInvoiceDetailEntity.getGoodsName());
            sellerRedInvoiceDetailEntity.setUnit(sellerInvoiceDetailEntity.getUnit());
            sellerRedInvoiceDetailEntity.setUnitPrice(sellerInvoiceDetailEntity.getUnitPrice());
            sellerRedInvoiceDetailEntity.setGoodNumber(sellerInvoiceDetailEntity.getGoodsNumber());
            sellerRedInvoiceDetailEntity.setGoodsSum(sellerInvoiceDetailEntity.getGoodsSum());
            sellerRedInvoiceDetailEntity.setTaxRate(sellerInvoiceDetailEntity.getTaxRate());
            sellerRedInvoiceDetailEntity.setGoodTax(sellerInvoiceDetailEntity.getGoodTax());
            sellerRedInvoiceDetailEntity.setTaxRateMark(sellerInvoiceDetailEntity.getTaxRateMark());
            sellerRedInvoiceDetailEntity.setPreferentialMark(sellerInvoiceDetailEntity.getPreferentialMark());
            sellerRedInvoiceDetailEntity.setPreferentialName(sellerInvoiceDetailEntity.getPreferentialName());
            sellerRedInvoiceDetailEntity.setTaxCode(sellerInvoiceDetailEntity.getTaxCode());
            sellerRedInvoiceDetailEntity.setDetailNo(sellerInvoiceDetailEntity.getDetailNo());
            sellerRedInvoiceDetailEntity.setSellerTaxNo(sellerInvoiceDetailEntity.getSellerTaxNo());
            sellerRedInvoiceDetailEntityList.add(sellerRedInvoiceDetailEntity);
        }
        redTicketService.save(sellerRedInvoiceEntity);
        sellerRedInvoiceDetailService.saveBatch(sellerRedInvoiceDetailEntityList);
        //查找所有与发票明细相同的红字明细
        List<SellerRedInvoiceDetailEntity> srdeList = sellerRedInvoiceDetailService.list(new QueryWrapper<SellerRedInvoiceDetailEntity>().in("uuid", idList));
        for (SellerRedInvoiceDetailEntity srde : srdeList) {
            srde.setRedMark("1");
            sellerRedInvoiceDetailService.updateById(srde);
        }
        SellerInvoiceEntity sie = this.getOne(new QueryWrapper<SellerInvoiceEntity>().eq("invoice_code", sellerInvoiceEntity.getInvoiceCode()).eq("invoice_no", sellerInvoiceEntity.getInvoiceNo()));
        sie.setInvoiceState("2");
        this.updateById(sie);
        //返回红字发票id,一步生成至待开
        ArrayList<String> ids = new ArrayList<>();
        ids.add(sellerRedInvoiceEntity.getUuid());
        return Response.success(ids);
    }


    /**
     * 特殊字符处理
     *
     * @param str
     * @return
     */
    public static boolean isSpecialChar(String str) {
        String regEx = "\\*";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.find();
    }

    /**
     * 作废红冲成功，更新docId表中的状态
     */
    public void updateCancelSuccessStatus(String docId, String invoiceType) {
        QueryWrapper<CancelDocDetailEntity> cancelQuery = new QueryWrapper<>();
        cancelQuery.eq("doc_id", docId);
        CancelDocDetailEntity cancelDocDetailEntity = new CancelDocDetailEntity();
        if (CodeConstant.INVOICETYPE_ZP.equals(invoiceType) || CodeConstant.INVOICETYPE_PP.equals(invoiceType)) {
            cancelDocDetailEntity.setCancelStatus(CodeConstant.YZF);
        } else if (CodeConstant.INVOICETYPE_DZFP.equals(invoiceType)) {
            cancelDocDetailEntity.setCancelStatus(CodeConstant.YHC);
        }
        cancelDocDetailMapper.update(cancelDocDetailEntity, cancelQuery);
    }

    /**
     * 作废红冲失败，更新docId表中的状态
     */
    public void updateCancelFailStatus(String docId) {
        QueryWrapper<CancelDocDetailEntity> cancelQuery = new QueryWrapper<>();
        cancelQuery.eq("doc_id", docId);
        CancelDocDetailEntity cancelDocDetailEntity = new CancelDocDetailEntity();
        cancelDocDetailEntity.setCancelStatus(CodeConstant.CLSB);
        cancelDocDetailMapper.update(cancelDocDetailEntity, cancelQuery);
    }

    /**
     * 待开发票类型修改
     *
     * @param updateInvoiceTypeDTO
     * @return
     */
    public Response updateInvoiceType(UpdateInvoiceTypeDTO updateInvoiceTypeDTO) {
        UpdateWrapper<SellerInvoiceEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("uuid", updateInvoiceTypeDTO.getUuid())
                .set("invoice_type", updateInvoiceTypeDTO.getInvoiceType());
        boolean result = this.update(new SellerInvoiceEntity(), updateWrapper);
        if (result) {
            return Response.success();
        }
        return Response.error();
    }

    /**
     * true 将商品名称已款项名称加款项类别
     *
     * @param projectCode
     * @return
     */
    private Boolean mergeOf(String projectCode) {
        QueryWrapper<SellerDetialMergeEntity> queryWrapper = new QueryWrapper();
        queryWrapper.eq("project_code_max", projectCode);
        List<SellerDetialMergeEntity> entitys = sellerDetialMergeService.list(queryWrapper);
        if (CollectionUtil.isEmpty(entitys)) {
            return false;
        } else {
            SellerDetialMergeEntity entity = entitys.get(0);
            if ("0".equals(entity.getIsMergeCategoryName())) {
                return false;
            } else if ("1".equals(entity.getIsMergeCategoryName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * pdf下载
     *
     * @param dto
     * @return
     */
    public Response downLoadPdf(InvoicedDTO dto) {
        String invoiceCode = dto.getInvoiceCode();
        String invoiceNo = dto.getInvoiceNo();
        if(StrUtil.isBlank(invoiceCode) || StrUtil.isBlank(invoiceNo)){
            return Response.error("SEL_107");
        }
        SellerInvoiceEntity invoiceEntity = baseMapper.selectOne(new QueryWrapper<SellerInvoiceEntity>().eq("invoice_code",invoiceCode).eq("invoice_no",invoiceNo));
        if(null == invoiceEntity){
            return Response.error("SEL_107");
        }
        EquipmentEntity equipmentEntity = equipmentService.getOne(new QueryWrapper<EquipmentEntity>().eq("seller_tax_no",invoiceEntity.getSellerTaxNo()).eq("disable","1"));
        if (equipmentEntity != null) {
            String appid = equipmentEntity.getAppid();
            String json = IntJsonUtil.getInvoicePdf(invoiceCode, invoiceNo, invoiceEntity.getSellerTaxNo(), appid);
            SellerInvoiceDTO sellerInvoiceDTO = new SellerInvoiceDTO();
            sellerInvoiceDTO.setBw(json);
            Response  response = apiClientService.callSST(sellerInvoiceDTO);
            String result = (String) response.getData();
            JSONObject jsonObject = (JSONObject) JSON.parse(result);
            String code = jsonObject.getString("code");
            String msg = jsonObject.getString("msg");
            if ("00000".equals(code)) {
                List resList = (List) jsonObject.get("data");
                if (CollectionUtils.isNotEmpty(resList)) {
                    Map pdfMap = (Map) resList.get(0);
                    String url = MapUtils.getString(pdfMap, "url", "");
                    response.setData(url);
                }
                return response;
            } else {
                return Response.error(msg);
            }
        } else {
            return Response.error("设备信息为空");
        }
    }

    /**
     * 乐企数电开票
     * @param serialNos
     * @return
     */
    public Response makeInvoice(List<String> serialNos){
        for (int i=0;i<serialNos.size();i++) {
            String serialNo = serialNos.get(i);
            try{
                Map<String, Object> para = new HashMap<>();
                para.put("serialNo", serialNo);
                List<SellerInvoiceEntity> invoicesList = baseMapper.selectInvoiceByMap(para);
                SellerInvoiceEntity invoice = new SellerInvoiceEntity();
                if (invoicesList != null && invoicesList.size() > 0) {
                    invoice = invoicesList.get(0);
                }
                Map<String,Object> fphmdDetailReq = new HashMap<>();
                fphmdDetailReq.put("status","0");
                fphmdDetailReq.put("nsrsbh",invoice.getSellerTaxNo());
                List<Map<String,Object>> fphmdDetailList = fphmdDetailMapper.selectFphmdDetailList(fphmdDetailReq);
                Map<String,Object> fphmdDetailMap = new HashMap<>();
                if(fphmdDetailList!=null && fphmdDetailList.size()!=0){
                    fphmdDetailMap = fphmdDetailList.get(0);
                }else{
                    return Response.error(CodeConstant.T0001, "无空白数电发票，请赋码");
                }

//                Map<String,Object> param = new HashMap<>();
//                param.put("nsrsbh",invoice.getSellerTaxNo());
//                param.put("sq",DateUtils.getDateToStr02());
//                List<OrganizeEntity> organizes = organizeMapper.selectOrganizeList(param);
//                if(organizes!=null && organizes.size()!=0){
//                    OrganizeEntity organize = organizes.get(0);
//                    BigDecimal kysyedB = new BigDecimal(organize.getKysyed());
//                    BigDecimal jshjB = new BigDecimal(invoice.getJshj());
//                    if(jshjB.compareTo(kysyedB)>0){
//                        resultMap.put("code","0002");
//                        resultMap.put("msg","已下载剩余授信额度不足,请先下载授信额度");
//                        break;
//                    }
//                }


                Map<String,Object> mxMap = new HashMap<>();
                mxMap.put("serialNo", serialNo);
                List<SellerInvoiceDetailEntity> details = invoiceDetailMapper.selectKpmxbBySsflbm(mxMap);

                String fphm = String.valueOf(fphmdDetailMap.get("fphm"));
                String kprq = DateUtils.getDateToStrHms();
                log.info("========数字化电子发票上传========开始======");
                JSONObject reqJson = new JSONObject();
                reqJson.put("fphm",fphm);//发票号码
                reqJson.put("lzfpbz",invoice.getMakeInvoiceType());//蓝字发票标志 0：蓝字发票 1：红字发票
                reqJson.put("ptbh",ptbh);//平台编号
                String fppz = "01";
                if("81".equals(invoice.getFplx())){
                    fppz = "01";
                }else if("82".equals(invoice.getFplx())){
                    fppz = "02";
                }
                reqJson.put("fppz",fppz);//发票票种 01：数字化电子专02：数字化电子普
                reqJson.put("qyDm","11400");//区域代码
                reqJson.put("xsfnsrsbh",invoice.getSellerTaxNo());//销方税号
                reqJson.put("xsfmc",invoice.getSellerName());//销方名称
                reqJson.put("gmfnsrsbh",invoice.getPurchaserTaxNo());//购方税号
                reqJson.put("gmfmc",invoice.getPurchaserName());//购方名称
                reqJson.put("hjje",invoice.getTotalSum());//合计金额
                reqJson.put("hjse",invoice.getTotalTax());//合计税额
                reqJson.put("jshj",invoice.getTotalSumTax());//价税合计1022.34
                reqJson.put("kpr",invoice.getDrawer());//开票人
                if("1".equals(invoice.getMakeInvoiceType())) {
                    reqJson.put("dylzfphm", invoice.getOldInvoiceNo());//对应蓝字发票号码
                    reqJson.put("hzqrxxdbh", invoice.getRedInfoNo());//红字确认信息单
                    reqJson.put("hzqrduuid", invoice.getInvoiceRecordNo());//红字确认单 uuid
                }
                reqJson.put("bz",invoice.getRemark());//备注
                reqJson.put("ip",ip);//服务器地址
                reqJson.put("macdz",macdz);//mac 地址
                reqJson.put("kprq",kprq);//开票日期

                int mxxh = 0;
                JSONArray mxArray = new JSONArray();
                for(SellerInvoiceDetailEntity d : details) {
                    mxxh = mxxh + 1;
                    JSONObject mxJson = new JSONObject();
                    if("1".equals(invoice.getMakeInvoiceType())) {
                        mxJson.put("mxxh", mxxh);//明细序号
                        mxJson.put("dylzfpmxxh", d.getDetailNo());//对应蓝字发票明细序号
                    }else{
                        mxJson.put("mxxh", d.getDetailNo());//明细序号
                    }
                    mxJson.put("xmmc", d.getGoodsName());//项目名称
                    mxJson.put("hwhyslwfwmc", "*"+d.getTaxOfName()+"*"+d.getGoodsName());//货物或应税劳务、服务名称
                    mxJson.put("spfwjc", d.getTaxOfName());//商品服务简称
                    mxJson.put("ggxh",d.getModel());//规格型号
                    mxJson.put("dw", d.getUnit());//单位
                    mxJson.put("sl", d.getGoodsNumber());//数量
                    mxJson.put("dj", d.getUnitPrice());//单价
                    mxJson.put("je", d.getGoodsSum());//金额
                    mxJson.put("slv", d.getTaxRate());//增值税税率/征收率
                    mxJson.put("se", d.getGoodTax());//税额
                    mxJson.put("hsje", d.getGoodsSumTax());//含税金额
                    //        mxJson.put("kce","200");//扣除额
                    mxJson.put("sphfwssflhbbm", d.getTaxCode());//商品和服务税收分类合并编码
                    mxJson.put("fphxz", d.getInvoiceRowNature());//发票行性质
                    if ("1".equals(d.getPreferentialMark())) {
                        mxJson.put("yhzcbs", "03");//优惠政策标识
                    } else if ("0".equals(d.getPreferentialMark())) {
                        mxJson.put("yhzcbs", "04");//优惠政策标识
                    }
                    mxArray.add(mxJson);
                }
                reqJson.put("fpmxList",mxArray);
                JSONArray jsonArray = new JSONArray();
                jsonArray.add(reqJson);
                String reqStr = jsonArray.toJSONString();
                log.info("========入参======>>>"+reqStr);
                url = url+"202007/QDFPSC";
                JSONObject result_json = lqHttpUtil.sendPostLq(reqStr,url);
                String returncode = result_json.getString("returncode");
                String msg = result_json.getString("msg");
                if("00".equals(returncode)) {
                    String sllsh = result_json.getString("sllsh");//开票成功，返回流水号
                    Map<String, Object> fphmdFetail_map = new HashMap<>();
                    fphmdFetail_map.put("fphm", fphm);
                    fphmdFetail_map.put("status", "1");//0未使用，1：使用中，2：已使用
                    fphmdFetail_map.put("updateDate", DateUtils.getDateToStrHms());
                    fphmdDetailMapper.updateFphmdDetailStatus(fphmdFetail_map);
                    //修改待开发票表
                    Map<String, Object> sstResMap = new HashMap<>();
                    sstResMap.put("failReason", "提交成功");
                    sstResMap.put("nowSid", sllsh);
                    sstResMap.put("serialNo", serialNo);
                    sstResMap.put("makeInvoiceState", "5");
                    sstResMap.put("invoiceNo", fphm);
                    sstResMap.put("invoiceDate", kprq);
                    baseMapper.updateInvoiceInfo(sstResMap);
                    return Response.success();
                } else {
                    log.info("开票接口错误，result：" + msg);
                    Map<String, Object> sstResMap = new HashMap<>();
                    sstResMap.put("failReason", msg);
                    sstResMap.put("serialNo", serialNo);
                    sstResMap.put("makeInvoiceState", "0");
                    baseMapper.updateInvoiceInfo(sstResMap);
                    return Response.error(CodeConstant.T0001, msg);
                }
            }catch (Exception e){
                log.error("数字化电子发票上传,异常：",e);
                Map<String,Object> sstResMap = new HashMap<>();
                sstResMap.put("failReason","接口异常");
                sstResMap.put("serialNo",serialNo);
                baseMapper.updateInvoiceInfo(sstResMap);
                e.printStackTrace();
                return Response.error(CodeConstant.ERROR, e.getMessage());
            }
        }
        return null;
    }

    /**
     * 整体数字化电子红字确认单申请
     * @param param
     * @return
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    public Response sqHcInvoice(Map<String, Object> param)  {
        log.info("========数字化电子红字确认单申请========开始======");
        String serialNo = (String) param.get("serialNo");// 流水号
        Map<String, Object> para = new HashMap<>();
        para.put("serialNo", serialNo);
        List<SellerInvoiceEntity> invoicesList = baseMapper.selectInvoiceByMap(para);
        List<SellerInvoiceDetailEntity> details = invoiceDetailMapper.selectKpmxbBySsflbm(para);
        try{
            if(invoicesList!=null && invoicesList.size()!=0) {
                SellerInvoiceEntity invoice = invoicesList.get(0);
                SellerInvoiceEntity invoice_new = invoicesList.get(0);//新的发票数据
                List<SellerInvoiceDetailEntity> details_new = new ArrayList<>();
                JSONObject reqJson = new JSONObject();
                reqJson.put("lrfsf", "0");//录入方身份0：销方1：购方
                reqJson.put("xsfnsrsbh", invoice.getSellerTaxNo());//（销售方）统一社会信用代码/纳税人识别号/身份证件号码
                reqJson.put("xsfmc", invoice.getSellerName());//（销售方）名称
                reqJson.put("gmfnsrsbh", invoice.getPurchaserTaxNo());//（购买方）统一社会信用代码/纳税人识别号/身份证件号码
                reqJson.put("gmfmc", invoice.getPurchaserName());//（购买方）名称
                reqJson.put("lzfphm", invoice.getInvoiceNo());//蓝字发票号码
                reqJson.put("sfzzfpbz", "N");//是否纸质发票标志Y：纸质发票N：电子发票
                reqJson.put("lzkprq", invoice.getInvoiceDate());//蓝字发票开票日期
                reqJson.put("lzhjje", invoice.getTotalSum());//蓝字发票合计金额
                reqJson.put("lzhjse", invoice.getTotalTax());//蓝字发票合计税额
                if (invoice.getFplx().equals("81")) {
                    reqJson.put("lzfppzDm", "01");//发票票种代码01: 增值税专用发票02: 普通发票03: 机动车统一销售发票04: 二手车统一销售发票05：铁路客票电子发票 06：航空运输电子客票行程单
                }
                if (invoice.getFplx().equals("82")) {
                    reqJson.put("lzfppzDm", "02");//发票票种代码01: 增值税专用发票02: 普通发票03: 机动车统一销售发票04: 二手车统一销售发票05：铁路客票电子发票 06：航空运输电子客票行程单
                }
                //        reqJson.put("lzfpTdyslxDm","01");//蓝字发票特定要素类型代码
                BigDecimal hzcxje = new BigDecimal(invoice.getTotalSum()).multiply(new BigDecimal(-1));
                BigDecimal hzcxse = new BigDecimal(invoice.getTotalTax()).multiply(new BigDecimal(-1));
                reqJson.put("hzcxje", hzcxje);//红字冲销金额
                reqJson.put("hzcxse", hzcxse);//红字冲销税额
                reqJson.put("chyyDm", String.valueOf(param.get("chyyDm")));//"01"红字发票冲红原因代码
                String uuid_new = invoice.getUuid()+"1";
                String serialNo_new = invoice.getSerialNo()+"1";
                invoice_new.setUuid(uuid_new);
                invoice_new.setSerialNo(serialNo_new);
                invoice_new.setTotalSum(hzcxje.toString());
                invoice_new.setTotalTax(hzcxse.toString());
                invoice_new.setTotalSumTax(new BigDecimal(invoice.getTotalSumTax()).multiply(new BigDecimal(-1)).toString());
                invoice_new.setOldInvoiceNo(invoice.getInvoiceNo());//原发票号码
                invoice_new.setMakeInvoiceState("0");
                invoice_new.setMakeInvoiceType("1");//开票类型（0 蓝票  1红票）
                invoice_new.setInvoiceDate("");
                invoice_new.setInvoiceNo("");

                JSONArray array = new JSONArray();
                for (int i = 0; i < details.size(); i++) {
                    SellerInvoiceDetailEntity mx = details.get(i);
                    SellerInvoiceDetailEntity mx_new = details.get(i);
                    String goodsNum = StringUtils.isNotEmpty(mx.getGoodsNumber()) ? mx.getGoodsNumber().trim() : "";//商品数量
                    String djNum = StringUtils.isNotEmpty(mx.getUnitPrice()) ? mx.getUnitPrice().trim() : "";
                    BigDecimal goodsNumB = new BigDecimal("0");
                    BigDecimal djB = new BigDecimal("0");
                    if (!"".equals(goodsNum) && !"".equals(djNum)) {
                        goodsNumB = new BigDecimal(goodsNum).multiply(new BigDecimal(-1));
                        djB = new BigDecimal(mx.getUnitPrice());
                    }else{
                        goodsNumB = new BigDecimal("0");
                        djB = new BigDecimal("0");
                    }
                    if(djB.scale() <= 0 || djB.stripTrailingZeros().scale() <= 0){
                        djB = djB.setScale(0, RoundingMode.DOWN);
                    }

                    String goodsCost = mx.getGoodsSum();//不含税金额
                    String goodsVat = mx.getGoodTax();//税额
                    String je = new BigDecimal(goodsCost).multiply(new BigDecimal(-1)).toString();
                    String se = new BigDecimal(goodsVat).multiply(new BigDecimal(-1)).toString();
                    JSONObject mxJson = new JSONObject();
                    mxJson.put("lzmxxh", mx.getDetailNo());//蓝字发票明细序号
                    mxJson.put("xh", mx.getDetailNo());//序号
                    mxJson.put("sphfwssflhbbm", mx.getTaxCode());//商品和服务税收分类合并编码
                    mxJson.put("hwhyslwfwmc", "*" + mx.getTaxOfName() + "*" + mx.getGoodsName());//货物或应税劳务、服务名称
                    mxJson.put("spfwjc", mx.getTaxOfName());//
                    mxJson.put("xmmc", mx.getGoodsName());//项目名称
                    mxJson.put("ggxh", mx.getModel());//规格型号
                    mxJson.put("dw", mx.getUnit());//单位
                    mxJson.put("fpspdj", djB);//单价
                    mxJson.put("fpspsl", goodsNumB);//数量
                    mxJson.put("je", je);//金额
                    mxJson.put("sl1", mx.getTaxRate());//税率
                    mxJson.put("se", se);//税额
                    array.add(mxJson);

                    mx_new.setUuid(UUIDUitl.UUID32(false));
                    mx_new.setSerialNo(serialNo_new);
                    mx_new.setGoodsNumber(goodsNumB.toString());
                    mx_new.setUnitPrice(djB.toString());
                    mx_new.setGoodsSum(je);
                    mx_new.setGoodTax(se);
                    mx_new.setGoodsSumTax(new BigDecimal(mx.getGoodsSumTax()).multiply(new BigDecimal(-1)).toString());
                    details_new.add(mx_new);
                }
                reqJson.put("hzqrdmxList", array);
                String reqStr = reqJson.toJSONString();
                log.info("========入参======>>>" + reqStr);
                url = url + "202007/QDHZQRDSQ";
                JSONObject result_json = lqHttpUtil.sendPostLq(reqStr,url);
                String returncode = result_json.getString("returncode");
                String msg01 = result_json.getString("msg");
                if("00".equals(returncode)) {
                    String hzfpxxqrdbh = result_json.getString("hzfpxxqrdbh");//红字确认单编号
                    String uuid = result_json.getString("uuid");//红字确认单 UUID
                    String hzqrxxztDm = result_json.getString("hzqrxxztDm");//红字确认单状态
                    //01：无需确认02：销方录入待购方确认03：购方录入待销方确认04：购销双方已确认
                    invoice_new.setInvoiceRecordNo(uuid);
                    invoice_new.setRedInfoNo(hzfpxxqrdbh);
                    invoice_new.setPrintState(hzqrxxztDm);//红字确认单状态
                    if("01".equals(hzqrxxztDm)||"04".equals(hzqrxxztDm)){
                        invoice_new.setMakeInvoiceState("0");//待开
                    }else if("02".equals(hzqrxxztDm)){
                        invoice_new.setMakeInvoiceState("4");//待购方确认
                    }
                    //新增申请到待开页面
                    baseMapper.insert(invoice_new);
                    for(SellerInvoiceDetailEntity detailEntity:details_new) {
                        invoiceDetailMapper.insert(detailEntity);
                    }

                    //修改原发票信息
                    Map<String, Object> cvMap = new HashMap<>();
                    cvMap.put("invoiceState", "2");
                    cvMap.put("serialNo", serialNo);
                    baseMapper.updateInvoiceInfo(cvMap);

                    return Response.success();
                }else{
                    log.info("开票接口错误，result：" + msg01);
                    return Response.error(CodeConstant.T0001, msg01);
                }
            }
        }catch (Exception e){
            log.error("数字化电子红字确认单申请,异常：",e);
            e.printStackTrace();
            return Response.error(CodeConstant.ERROR, e.getMessage());
        }
        log.info("========数字化电子红字确认单申请========结束======");
        return null;
    }

    /**
     * 部分红冲申请
     * @param invoice
     * @return
     */
    public Response bfSqHcInvoice(SellerInvoiceEntity invoice)  {
        log.info("====部分====数字化电子红字确认单申请========开始======");
        try{
            List<SellerInvoiceDetailEntity> details = invoice.getInvoiceDetail();
            SellerInvoiceEntity invoice_new = invoice;//新的发票数据
            List<SellerInvoiceDetailEntity> details_new = new ArrayList<>();
            JSONObject reqJson = new JSONObject();
            reqJson.put("lrfsf", "0");//录入方身份0：销方1：购方
            reqJson.put("xsfnsrsbh", invoice.getSellerTaxNo());//（销售方）统一社会信用代码/纳税人识别号/身份证件号码
            reqJson.put("xsfmc", invoice.getSellerName());//（销售方）名称
            reqJson.put("gmfnsrsbh", invoice.getPurchaserTaxNo());//（购买方）统一社会信用代码/纳税人识别号/身份证件号码
            reqJson.put("gmfmc", invoice.getPurchaserName());//（购买方）名称
            reqJson.put("lzfphm", invoice.getInvoiceNo());//蓝字发票号码
            reqJson.put("sfzzfpbz", "N");//是否纸质发票标志Y：纸质发票N：电子发票
            reqJson.put("lzkprq", invoice.getInvoiceDate());//蓝字发票开票日期
            reqJson.put("lzhjje", invoice.getTotalSum());//蓝字发票合计金额
            reqJson.put("lzhjse", invoice.getTotalTax());//蓝字发票合计税额
            if (invoice.getFplx().equals("81")) {
                reqJson.put("lzfppzDm", "01");//发票票种代码01: 增值税专用发票02: 普通发票03: 机动车统一销售发票04: 二手车统一销售发票05：铁路客票电子发票 06：航空运输电子客票行程单
            }
            if (invoice.getFplx().equals("82")) {
                reqJson.put("lzfppzDm", "02");//发票票种代码01: 增值税专用发票02: 普通发票03: 机动车统一销售发票04: 二手车统一销售发票05：铁路客票电子发票 06：航空运输电子客票行程单
            }
            //        reqJson.put("lzfpTdyslxDm","01");//蓝字发票特定要素类型代码
            BigDecimal hzcxje = new BigDecimal(invoice.getTotalSum());
            BigDecimal hzcxse = new BigDecimal(invoice.getTotalTax());
            reqJson.put("hzcxje", hzcxje);//红字冲销金额
            reqJson.put("hzcxse", hzcxse);//红字冲销税额
            reqJson.put("chyyDm", invoice.getChyyDm());//"01"红字发票冲红原因代码
            String uuid_new = invoice.getUuid()+"1";
            String serialNo_new = invoice.getSerialNo()+"1";
            invoice_new.setUuid(uuid_new);
            invoice_new.setSerialNo(serialNo_new);
            invoice_new.setTotalSum(hzcxje.toString());
            invoice_new.setTotalTax(hzcxse.toString());
            invoice_new.setTotalSumTax(invoice.getTotalSumTax());
            invoice_new.setOldInvoiceNo(invoice.getInvoiceNo());//原发票号码
            invoice_new.setMakeInvoiceState("0");
            invoice_new.setMakeInvoiceType("1");//开票类型（0 蓝票  1红票）
            invoice_new.setInvoiceDate("");
            invoice_new.setInvoiceNo("");

            JSONArray array = new JSONArray();
            for (int i = 0; i < details.size(); i++) {
                SellerInvoiceDetailEntity mx = details.get(i);
                SellerInvoiceDetailEntity mx_new = details.get(i);
                String goodsNum = StringUtils.isNotEmpty(mx.getGoodsNumber()) ? mx.getGoodsNumber().trim() : "";//商品数量
                String djNum = StringUtils.isNotEmpty(mx.getUnitPrice()) ? mx.getUnitPrice().trim() : "";
                BigDecimal goodsNumB = new BigDecimal("0");
                BigDecimal djB = new BigDecimal("0");
                if (!"".equals(goodsNum) && !"".equals(djNum)) {
                    goodsNumB = new BigDecimal(goodsNum);
                    djB = new BigDecimal(mx.getUnitPrice());
                }else{
                    goodsNumB = new BigDecimal("0");
                    djB = new BigDecimal("0");
                }
                if(djB.scale() <= 0 || djB.stripTrailingZeros().scale() <= 0){
                    djB = djB.setScale(0, RoundingMode.DOWN);
                }

                String goodsCost = mx.getGoodsSum();//不含税金额
                String goodsVat = mx.getGoodTax();//税额
                String je = new BigDecimal(goodsCost).toString();
                String se = new BigDecimal(goodsVat).toString();
                JSONObject mxJson = new JSONObject();
                mxJson.put("lzmxxh", mx.getDetailNo());//蓝字发票明细序号
                mxJson.put("xh", mx.getDetailNo());//序号
                mxJson.put("sphfwssflhbbm", mx.getTaxCode());//商品和服务税收分类合并编码
                mxJson.put("hwhyslwfwmc", "*" + mx.getTaxOfName() + "*" + mx.getGoodsName());//货物或应税劳务、服务名称
                mxJson.put("spfwjc", mx.getTaxOfName());//
                mxJson.put("xmmc", mx.getGoodsName());//项目名称
                mxJson.put("ggxh", mx.getModel());//规格型号
                mxJson.put("dw", mx.getUnit());//单位
                mxJson.put("fpspdj", djB);//单价
                mxJson.put("fpspsl", goodsNumB);//数量
                mxJson.put("je", je);//金额
                mxJson.put("sl1", mx.getTaxRate());//税率
                mxJson.put("se", se);//税额
                array.add(mxJson);

                mx_new.setUuid(UUIDUitl.UUID32(false));
                mx_new.setSerialNo(serialNo_new);
                mx_new.setGoodsNumber(goodsNumB.toString());
                mx_new.setUnitPrice(djB.toString());
                mx_new.setGoodsSum(je);
                mx_new.setGoodTax(se);
                mx_new.setGoodsSumTax(mx.getGoodsSumTax());
                details_new.add(mx_new);
            }
            reqJson.put("hzqrdmxList", array);
            String reqStr = reqJson.toJSONString();
            log.info("========入参======>>>" + reqStr);
            url = url + "202007/QDHZQRDSQ";
            JSONObject result_json = lqHttpUtil.sendPostLq(reqStr,url);
            String returncode = result_json.getString("returncode");
            String msg01 = result_json.getString("msg");
            if("00".equals(returncode)) {
                String hzfpxxqrdbh = result_json.getString("hzfpxxqrdbh");//红字确认单编号
                String uuid = result_json.getString("uuid");//红字确认单 UUID
                String hzqrxxztDm = result_json.getString("hzqrxxztDm");//红字确认单状态
                //01：无需确认02：销方录入待购方确认03：购方录入待销方确认04：购销双方已确认
                invoice_new.setInvoiceRecordNo(uuid);
                invoice_new.setRedInfoNo(hzfpxxqrdbh);
                invoice_new.setPrintState(hzqrxxztDm);//红字确认单状态
                if("01".equals(hzqrxxztDm)||"04".equals(hzqrxxztDm)){
                    invoice_new.setMakeInvoiceState("0");//待开
                }else if("02".equals(hzqrxxztDm)){
                    invoice_new.setMakeInvoiceState("4");//待购方确认
                }
                //新增申请到待开页面
                baseMapper.insert(invoice_new);
                for(SellerInvoiceDetailEntity detailEntity:details_new) {
                    invoiceDetailMapper.insert(detailEntity);
                }

                //修改原发票信息
                Map<String, Object> cvMap = new HashMap<>();
                cvMap.put("invoiceState", "2");
                cvMap.put("serialNo", invoice.getSerialNo());
                baseMapper.updateInvoiceInfo(cvMap);

                return Response.success();
            }else{
                log.info("开票接口错误，result：" + msg01);
                return Response.error(CodeConstant.T0001, msg01);
            }
        }catch (Exception e){
            log.error("数字化电子红字确认单申请,异常：",e);
            e.printStackTrace();
            return Response.error(CodeConstant.ERROR, e.getMessage());
        }
    }


    /**
     * 乐企红冲
     * @param param
     * @return
     */
    public Response hcRedInvoice(Map<String, Object> param) {
        String serialNo = String.valueOf(param.get("serialNo"));
        String new_serialNo =serialNo+"1";
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("serialNo", serialNo);
        List<SellerInvoiceEntity> invoicesList = baseMapper.selectInvoiceByMap(paraMap);
        SellerInvoiceEntity invoice = new SellerInvoiceEntity();
        if (invoicesList != null && invoicesList.size() > 0) {
            invoice = invoicesList.get(0);
        }
        Map<String,Object> mxMap = new HashMap<>();
        mxMap.put("serialNo", serialNo);
        List<SellerInvoiceDetailEntity> details = invoiceDetailMapper.selectKpmxbBySsflbm(mxMap);
        String yfphm = invoice.getInvoiceNo();
        BigDecimal hjjeB = new BigDecimal(invoice.getTotalSum());
        BigDecimal hjjeBN = NumberUtil.mul(hjjeB, -1);
        BigDecimal hjseB = new BigDecimal(invoice.getTotalTax());
        BigDecimal hjseBN = NumberUtil.mul(hjseB, -1);
        BigDecimal jshjB = new BigDecimal(invoice.getTotalSumTax());
        BigDecimal jshjBN = NumberUtil.mul(jshjB, -1);

        invoice.setTotalSum(hjjeBN.toString());
        invoice.setTotalTax(hjseBN.toString());
        invoice.setTotalSumTax(jshjBN.toString());
        invoice.setOldInvoiceCode(yfphm);
        invoice.setSerialNo(new_serialNo);
        invoice.setMakeInvoiceType("1");
        invoice.setMakeInvoiceState("5");
        List<SellerInvoiceDetailEntity> kpmxbList = new ArrayList<>();
        for (int i = 0; i < details.size(); i++) {
            SellerInvoiceDetailEntity detail = details.get(i);
            String sl = detail.getGoodsNumber();
            String se = detail.getGoodTax();
            BigDecimal seB = NumberUtil.round(se,2);
            if (notEmpty(sl)) {
                sl = "-" + sl;
            }
            BigDecimal je = new BigDecimal(detail.getGoodsSumTax());
            je = je.multiply(new BigDecimal("-1"));
            BigDecimal se_b = new BigDecimal(se).multiply(new BigDecimal("-1"));
            detail.setGoodsSumTax(je.toString());
            detail.setGoodTax(se_b.toString());
            if (seB.doubleValue() == 0.0) {
                detail.setGoodTax("0.00");
            }
            detail.setSerialNo(new_serialNo);
            detail.setUuid(UUIDUitl.UUID32());
            detail.setGoodsNumber(sl);
            kpmxbList.add(detail);
        }
        Map<String,Object> fphmdDetailReq = new HashMap<>();
        fphmdDetailReq.put("status","0");
        fphmdDetailReq.put("nsrsbh",invoice.getSellerCode());
        List<Map<String,Object>> fphmdDetailList = fphmdDetailMapper.selectFphmdDetailList(fphmdDetailReq);
        Map<String,Object> fphmdDetailMap = new HashMap<>();
        if(fphmdDetailList!=null && fphmdDetailList.size()!=0){
            fphmdDetailMap = fphmdDetailList.get(0);
        }
        String fphm = String.valueOf(fphmdDetailMap.get("fphm"));
        String kprq = DateUtils.getDateToStrHms();
        log.info("========数字化电子发票红冲上传========开始======");
        JSONObject reqJson = new JSONObject();
        reqJson.put("fphm",fphm);//发票号码
        reqJson.put("lzfpbz",invoice.getInvoiceState());//蓝字发票标志 0：蓝字发票 1：红字发票
        reqJson.put("ptbh",ptbh);//平台编号
        String fppz = "01";
        if("81".equals(invoice.getFplx())){
            fppz = "01";
        }else if("82".equals(invoice.getFplx())){
            fppz = "02";
        }
        reqJson.put("fppz",fppz);//发票票种 01：数字化电子专02：数字化电子普
        reqJson.put("qyDm","11400");//区域代码
        reqJson.put("xsfnsrsbh",invoice.getSellerTaxNo());//销方税号
        reqJson.put("xsfmc",invoice.getSellerName());//销方名称
        reqJson.put("gmfnsrsbh",invoice.getPurchaserTaxNo());//购方税号
        reqJson.put("gmfmc",invoice.getPurchaserName());//购方名称
        reqJson.put("hjje",invoice.getTotalSum());//合计金额
        reqJson.put("hjse",invoice.getTotalTax());//合计税额
        reqJson.put("jshj",invoice.getTotalSumTax());//价税合计1022.34
        reqJson.put("kpr",invoice.getDrawer());//开票人
        if("1".equals(invoice.getMakeInvoiceType())) {
            reqJson.put("dylzfphm", invoice.getOldInvoiceNo());//对应蓝字发票号码
            reqJson.put("hzqrxxdbh", invoice.getRedInfoNo());//红字确认信息单
            reqJson.put("hzqrduuid", invoice.getInvoiceRecordNo());//红字确认单 uuid
        }
        reqJson.put("bz",invoice.getRemark());//备注
        reqJson.put("ip",ip);//服务器地址
        reqJson.put("macdz",macdz);//mac 地址
        reqJson.put("kprq",kprq);//开票日期

        JSONArray mxArray = new JSONArray();
        for(SellerInvoiceDetailEntity d : details) {
            JSONObject mxJson = new JSONObject();
            mxJson.put("mxxh", d.getDetailNo());//明细序号
            if("1".equals(invoice.getMakeInvoiceType())) {
                mxJson.put("dylzfpmxxh", d.getDetailNo());//对应蓝字发票明细序号
            }
            mxJson.put("xmmc", d.getGoodsName());//项目名称
            mxJson.put("hwhyslwfwmc", "*"+d.getTaxOfName()+"*"+d.getGoodsName());//货物或应税劳务、服务名称
            mxJson.put("spfwjc", d.getTaxOfName());//商品服务简称
            mxJson.put("ggxh",d.getModel());//规格型号
            mxJson.put("dw", d.getUnit());//单位
            mxJson.put("sl", d.getGoodsNumber());//数量
            mxJson.put("dj", d.getUnitPrice());//单价
            mxJson.put("je", d.getGoodsSum());//金额
            mxJson.put("slv", d.getTaxRate());//增值税税率/征收率
            mxJson.put("se", d.getGoodTax());//税额
            mxJson.put("hsje", d.getGoodsSumTax());//含税金额
            mxJson.put("sphfwssflhbbm", d.getTaxCode());//商品和服务税收分类合并编码
            mxJson.put("fphxz", d.getInvoiceRowNature());//发票行性质
            mxArray.add(mxJson);
        }
        reqJson.put("fpmxList",mxArray);
        JSONArray jsonArray = new JSONArray();
        jsonArray.add(reqJson);
        String reqStr = jsonArray.toJSONString();
        log.info("========入参======>>>"+reqStr);
        try {
            url = url+"202007/QDFPSC";
            JSONObject result_json = lqHttpUtil.sendPostLq(reqStr,url);
            String returncode = result_json.getString("returncode");
            String msg01 = result_json.getString("msg");
            if("00".equals(returncode)) {
                String sllsh = result_json.getString("sllsh");//开票成功，返回流水号
                Map<String, Object> fphmdFetail_map = new HashMap<>();
                fphmdFetail_map.put("fphm", fphm);
                fphmdFetail_map.put("status", "1");//0未使用，1：使用中，2：已使用
                fphmdFetail_map.put("updateDate", DateUtils.getDateToStrHms());
                fphmdDetailMapper.updateFphmdDetailStatus(fphmdFetail_map);
                invoice.setInvoiceNo(fphm);
                invoice.setInvoiceDate(kprq);
                invoice.setNowSid(sllsh);
                baseMapper.insert(invoice);
                for(SellerInvoiceDetailEntity detail : kpmxbList){
                    invoiceDetailMapper.insert(detail);
                }
                return Response.success();
            } else {
                log.info("接口异常，result：" + msg01);
                return Response.error("接口异常:"+msg01);
            }
        }catch (Exception e){
            log.info("接口异常，result："+e);
            e.printStackTrace();
            return Response.error(CodeConstant.ERROR, e.getMessage());
        }

    }

    /**
     * 获取发票信息
     * @param param
     * @return
     */
    public Response getInvoice(Map<String, Object> param) {
        String serialNo = String.valueOf(param.get("serialNo"));
        Map<String, Object> paraMap = new HashMap<>();
        paraMap.put("serialNo", serialNo);
        List<SellerInvoiceEntity> invoicesList = baseMapper.selectInvoiceByMap(paraMap);
        SellerInvoiceEntity invoice = new SellerInvoiceEntity();
        if (invoicesList != null && invoicesList.size() > 0) {
            invoice = invoicesList.get(0);
        }
        Map<String, Object> mxMap = new HashMap<>();
        mxMap.put("serialNo", serialNo);
        List<SellerInvoiceDetailEntity> details = invoiceDetailMapper.selectKpmxbBySsflbm(mxMap);
        invoice.setInvoiceDetail(details);
        return  Response.success(invoice);
    }

    /**
     * 检测字符串是否不为空(null,"","null")
     *
     * @param s
     * @return 不为空则返回true，否则返回false
     */
    public static boolean notEmpty(String s) {
        return s != null && !"".equals(s) && !"null".equals(s) && !"undefined".equals(s);
    }
}
